RememberMarkerState doesn't work correctly
Hey there ✋🏻
We have developed an application using Compose and using version 5.0.1 for the map screen and to add markers.
After moving and stopping, we make a request to the server and receive a response with a list of markers. We map these to the UI model and try to draw them on the map as shown below:
GoogleMap(
modifier = modifier,
cameraPositionState = cameraPositionState,
properties = mapProperties,
uiSettings = uiSettings,
onMapClick = { onMapClick() },
onMapLoaded = {
onMapLoaded(
LocationLatLng(
cameraPositionState.position.target.latitude,
cameraPositionState.position.target.longitude
),
cameraPositionState.visibleAreaAsRadius(defaultVisibleAreaDistance)
)
}
) {
markers?.forEach { marker ->
MarkerComposable(
state = rememberMarkerState(
key = marker.key,
position = LatLng(
marker.position.latitude,
marker.position.longitude
),
),
onClick = {
marker.onMarkerClick()
return@MarkerComposable false
}
) {
Image(
modifier = Modifier.size(64.dp),
painter = painterResource(marker.iconResId),
contentDescription = marker.contentDescriptionResId?.let { stringResource(it) },
)
}
}
}
...
}
However, I sometimes notice that even if the markers are in the list, they do not get drawn on the map screen. What could be the reason for this?
Thanks in advance.
Note: Marker keys are unique.
https://github.com/googlemaps/android-maps-compose/assets/12996047/e573fa6d-920a-4b42-9bd4-c366f51eb5ad
Hi, I just updated to v6.0.0 and encountered a similar issue (or the same maybe). A workaround that works for me is putting the Marker inside a key block, maybe it will also work for you ?
markers?.forEach { marker ->
key(marker.key) {
MarkerComposable(
state = rememberMarkerState(
position = LatLng(
marker.position.latitude,
marker.position.longitude
),
),
onClick = {
marker.onMarkerClick()
return@MarkerComposable false
}
) {
Image(
modifier = Modifier.size(64.dp),
painter = painterResource(marker.iconResId),
contentDescription = marker.contentDescriptionResId?.let { stringResource(it) },
)
}
}
}
I recommend not using rememberMarkerState(), and replacing it with remember { MarkerState(...) }, as the former uses rememberSaveable, which is not what you want when you render markers from a model.
My blog post on the topic may be of help: https://dev.to/bubenheimer/effective-map-composables-non-draggable-markers-2b2
Not sure if this will fix your problem, but it will be a good start.
Also, I don't think the key in rememberSaveable/rememberMarkerState works like a key() block, so the latter will help indeed.
Thanks, that's what I needed to make markers work like they should.
Thank you @kevin68 @bubenheimer 🙏🏻
This issue is still there. @fevziomurtekin can you re-open the issue? 😄 imo, an available workaround isn't a proper resolution. Google Maps team should fix this on their end