Home > database >  Animate Compose GoogleMap to a Specified Location
Animate Compose GoogleMap to a Specified Location

Time:08-16

I am working on a simple Maps App and I am trying to make GoogleMap composable zoom-inanimation over 1000 ms duration.

So far I have this code:

Column( ... ) {

                val destinationLatLng = LatLng(destination.lat, destination.lng)
                
                val cameraPositionState = rememberCameraPositionState {
                    position = CameraPosition.fromLatLngZoom(destinationLatLng, 15f)

                }

                GoogleMap(
                        modifier = Modifier.fillMaxSize(),
                        cameraPositionState = cameraPositionState
                        //stuck on animating this
                )

            }

In the old good GoogleMap view I could animate the camera with this sample code.

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition), 1000, null)

However, in Compose I am unable to re-engineer this to achieve the zoom-in animation.

I have looked at the docs for Compose for the Maps SDK and Maps Compose Library but I am still stuck.

Please let me know if there is a way to animate camera in Compose GoogleMap

CodePudding user response:

If it's one and only one time animation when your Composable is composed use LaunchEffect(key1 = true) as the code shows below.

val initialZoom = 6f
val finalZoom = 15f
val destinationLatLng = LatLng(destination.lat, destination.lng)

val cameraPositionState = rememberCameraPositionState {
    position = CameraPosition.fromLatLngZoom(destinationLatLng, initialZoom)
}

LaunchedEffect(key1 = true) {
    cameraPositionState.animate(
        update = CameraUpdateFactory.newCameraPosition(
            CameraPosition(destinationLatLng, finalZoom, 0f, 0f)
        ),
        durationMs = 1000
    )
}

GoogleMap(
    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState
)
  • Related