Skip to content

Capture a map image

Use MapSnapshotter to create a map image for a preview or sharing. It renders a BaseStyle and a content block to an ImageBitmap without displaying a map.

To match a displayed map, pass the same base style and content function, then copy its camera position into the capture request. Compose overlays are not part of the captured image.

Create and close the snapshotter in a coroutine. MapSnapshotter.capture suspends until the image is ready:

App.kt
suspend fun captureCurrentMap(
runtime: MapRuntime,
mapState: MapState,
content: @Composable @MaplibreComposable () -> Unit,
density: Density,
layoutDirection: LayoutDirection,
): ImageBitmap {
val snapshotter =
runtime.createSnapshotter(
baseStyle = mapState.style.baseStyle,
content = content,
)
return try {
val captureDensity = density
val captureLayoutDirection = layoutDirection
snapshotter.capture(DpSize(640.dp, 360.dp)) {
cameraPosition = mapState.cameraPosition
this.density = captureDensity
this.layoutDirection = captureLayoutDirection
}
} finally {
withContext(NonCancellable) {
snapshotter.close()
snapshotter.awaitClosed()
}
}
}

The request size is in dp, and the image is that size multiplied by the request’s pixel density. Pass LocalDensity.current and LocalLayoutDirection.current from the calling composable to match the displayed map’s sizing and layout direction.

For repeated captures, keep one snapshotter and call capture again with a new request. Follow the same cleanup pattern as the example when its owner finishes using it.