Show Raster Image on the Map

Raster Overlay

This example shows how to add a raster overlay to the map. The image is deployed to the device as a bundled resource. You will need a raster and its bounding rectangle in geographic coordinates.

You will learn the following:

  • How to load raster from file (bundled as a local asset on the device).
  • How to create raster layer and draw it on the map.

Include Raster to the project

In Android Studio, copy your raster file into assets folder (create assets folder if it does not exists). The path should be app/src/main/assets.

Add the raster overlay

The overlay should be added after the map view is initialized and finishes loading the style. We implement callback in our fragment by inheriting from OnMapReadyCallback and implementing onMapReady function.

class RasterOverlayFragment : Fragment(), OnMapReadyCallback {
    ...
    override fun onMapReady(mapboxMap: MapboxMap) {
        ...
    }
    ...
}

Map Ready callback

The onMapReady callback looks as follows:

override fun onMapReady(mapboxMap: MapboxMap) {

        val mapTilerKey = Helper.getMapTilerKey(context!!)
        Helper.validateKey(mapTilerKey)
        val styleUrl = "https://api.maptiler.com/maps/streets/style.json?key=${mapTilerKey}"

        // Navigate the map to the area with raster data
        mapboxMap.cameraPosition = CameraPosition.Builder()
            .target(LatLng(50.90013625, 4.64086758))
            .zoom(17.0)
            .build()

        mapboxMap.setStyle(styleUrl) {
            addRasterLayer(it)
        }
    }

Raster layer

In order to display the image on map, it is necessary to set the image extent in geographic coordinates. Then we read the image using stream and create bitmap from it. Finally, we add the source and layer to the map.

private fun addRasterLayer(style: Style) {
        // Set the latitude and longitude values for the image's four corners
        val quad = LatLngQuad(
            LatLng(50.900867668253724, 4.639663696289062),
            LatLng(50.900867668253724, 4.642066955566406),
            LatLng(50.89935199434383, 4.642066955566406),
            LatLng(50.89935199434383, 4.639663696289062)
        )

        val inputStream: InputStream = context!!.assets.open("aerial_wgs84.png")
        val bitmap = BitmapFactory.decodeStream(inputStream)
        // Add an ImageSource to the map
        style.addSource(ImageSource("raster-image-source", quad, bitmap))

        // Create a raster layer and use the imageSource's ID as the layer's data. Then add a RasterLayer to the map.
        style.addLayer(RasterLayer("raster-image-layer", "raster-image-source"))
    }