diff --git a/README.md b/README.md index 1a822ecc..b72c63f0 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,26 @@ Box(Modifier.fillMaxSize()) { } ``` +Remember that the map must load before any camera state can be set. If you are using a LaunchedEffect, you must wait until the map has been loaded: + +```kotlin +@Composable +fun MapScreen() { +var mapLoaded by remember { mutableStateOf(false) } + + GoogleMap( + modifier = Modifier.fillMaxSize(), + onMapLoaded = { mapLoaded = true } + ) + + if (mapLoaded) { + LaunchedEffect(Unit) { + // here the camera operations + } + } +} +``` +
diff --git a/maps-app/src/main/java/com/google/maps/android/compose/LocationTrackingActivity.kt b/maps-app/src/main/java/com/google/maps/android/compose/LocationTrackingActivity.kt index 57276da3..a900ec8a 100644 --- a/maps-app/src/main/java/com/google/maps/android/compose/LocationTrackingActivity.kt +++ b/maps-app/src/main/java/com/google/maps/android/compose/LocationTrackingActivity.kt @@ -93,14 +93,16 @@ class LocationTrackingActivity : ComponentActivity() { // Collect location updates val locationState = locationFlow.collectAsState(initial = newLocation()) - // Update blue dot and camera when the location changes - LaunchedEffect(locationState.value) { - Log.d(TAG, "Updating blue dot on map...") - locationSource.onLocationChanged(locationState.value) - - Log.d(TAG, "Updating camera position...") - val cameraPosition = CameraPosition.fromLatLngZoom(LatLng(locationState.value.latitude, locationState.value.longitude), zoom) - cameraPositionState.animate(CameraUpdateFactory.newCameraPosition(cameraPosition), 1_000) + if (isMapLoaded) { + // Update blue dot and camera when the location changes + LaunchedEffect(locationState.value) { + Log.d(TAG, "Updating blue dot on map...") + locationSource.onLocationChanged(locationState.value) + + Log.d(TAG, "Updating camera position...") + val cameraPosition = CameraPosition.fromLatLngZoom(LatLng(locationState.value.latitude, locationState.value.longitude), zoom) + cameraPositionState.animate(CameraUpdateFactory.newCameraPosition(cameraPosition), 1_000) + } } // Detect when the map starts moving and print the reason diff --git a/maps-compose/src/main/java/com/google/maps/android/compose/CameraPositionState.kt b/maps-compose/src/main/java/com/google/maps/android/compose/CameraPositionState.kt index 98f07ada..b5730a9a 100644 --- a/maps-compose/src/main/java/com/google/maps/android/compose/CameraPositionState.kt +++ b/maps-compose/src/main/java/com/google/maps/android/compose/CameraPositionState.kt @@ -43,7 +43,8 @@ import kotlin.coroutines.resumeWithException /** * Create and [rememberSaveable] a [CameraPositionState] using [CameraPositionState.Saver]. * [init] will be called when the [CameraPositionState] is first created to configure its - * initial state. + * initial state. Remember that the camera state can be applied when the map has been + * loaded. */ @Composable public inline fun rememberCameraPositionState(