If you're using Google Maps Compose Library, the CameraPositionState
contains a Projection
which contains a VisibleRegion
which contains a LatLngBounds
.
If you pass in an onMapLoaded
function to the GoogleMap
composable (along with a cameraPositionState
), you can check this value.
You can also set up a LaunchedEffect
that triggers whenever the camera moves to report the bounds whenever it changes.
I used the following dependencies at the time I'm writing this
- Jetpack Compose: 1.2.0-beta02
- Kotlin: 1.6.21
- Maps Compose: 2.2.1
- Play Services Maps:18.0.2
See the Maps Compose Repo Install Instructions for up-to-date requirements.
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Maps1Theme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
// a simple UI that shows the LatLngBounds at the top
// and a map below it
var text by remember { mutableStateOf("") }
Column {
Text(
text = text,
modifier = Modifier.padding(8.dp)
)
Map(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
) {
text = it.toString()
}
}
}
}
}
}
}
@Composable
fun Map(
modifier: Modifier,
onBoundsChange: (LatLngBounds?) -> Unit,
) {
val cameraPositionState = rememberCameraPositionState {
position = CameraPosition.fromLatLngZoom(
LatLng(37.42423291057923, -122.08811454627153),
16f
)
}
// whenever cameraPositionState.isMoving changes, launch a coroutine
// to fire onBoundsChange. We'll report the visibleRegion
// LatLngBounds
LaunchedEffect(cameraPositionState.isMoving) {
if (!cameraPositionState.isMoving) {
onBoundsChange(
cameraPositionState.projection?.visibleRegion?.latLngBounds
)
}
}
GoogleMap(
modifier = modifier,
cameraPositionState = cameraPositionState,
// pass in an onMapLoaded to report the initial visible region
onMapLoaded = {
onBoundsChange(
cameraPositionState.projection?.visibleRegion?.latLngBounds
)
}
)
}