Search code examples
kotlinscreenshotmapbox-android

Screenshot of Mapbox map without displaying it


I need to display a few previews of addresses on the map on the same screen. To do that I'm going to display ImageViews with bitmaps instead of making multiple instances of MapView. But for that I need to find a way to capture these bitmaps.

I found snapshot function in MapboxMap (https://github.com/mapbox/mapbox-gl-native/issues/6062), but it requires displaying of the map.

val position = CameraPosition.Builder()
        .target(addressLatLng)
        .zoom(zoom)
        .build()
mapboxMap.cameraPosition = position

mapboxMap.snapshot { bitmap: Bitmap ->
    imageView.setImageBitmap(bitmap)
}

So, can I take a snapshot of the map without displaying it on the screen?


Solution

  • I've finally found the solution! The class I needed to use was MapSnapshotter.

    val width = imageView.width
    val height = imageView.height
    val location = CameraPosition.Builder()
            .target(LatLng(55.7558, 37.6173))
            .zoom(16.0)
            .build()
    val options = MapSnapshotter.Options(width, height)
            .withCameraPosition(location)
    MapSnapshotter(context, options).start { snapshot ->
        imageView.setImageBitmap(snapshot.bitmap)
    }