androidgoogle-mapsandroid-jetpack-compose

MarkerComposable (Google Maps) doesn't update marker's position even when recomposition happening due to key changes


I have a simple MarkerComposable as such

MarkerComposable(
        keys = arrayOf(position), // position is LatLng
        state = rememberMarkerState(
            key = position.latitude.toString() + position.longitude.toString(),
            position = position
        ),

    ) {
        content()
    }

When the position is changed, even though I can see a recomposition happens, marker's position is not updated on the map. I'm even setting the position as the keys (as explained here). This means that when the position is changed, the key is changed, and the location of the marker should get updated. But it doesn't.

Is there anything else I missed?


Solution

  • I found that it's actually due to rememberMarkerState. There is a detailed article about it here. But in short, this fixes the issue

    @Composable
        private fun rememberUpdatedMarkerState(newPosition: LatLng): MarkerState =
            remember { MarkerState(position = newPosition) }
                .apply { position = newPosition }
    
    val state = rememberUpdatedMarkerState(position)
    MarkerComposable(
        keys = keys,
        state = state,
    ) {
        content()
    }