Search code examples
androidkotlinmapboxmapbox-android

How do I grey out an area outside of a polygon in MapBox for Android?


I am currently using MapBox maps for Android v10.3.0. My app is written in Kotlin.

Using the PolygonAnnotation, PolygonAnnotationManager, and PolygonAnnotationOptions I am able to draw and shade a polygon on the map.

Example:

    // Create an instance of the Annotation API and get the polygon manager.
    val annotationApi = mapView.annotations
    val polygonAnnotationManager = annotationApi.createPolygonAnnotationManager()
    // Define a list of geographic coordinates to be connected.
    val points = listOf(
      listOf(
        Point.fromLngLat(17.94, 59.25),
        Point.fromLngLat(18.18, 59.25),
        Point.fromLngLat(18.18, 59.37),
        Point.fromLngLat(17.94, 59.37)
      )
    )
    // Set options for the resulting fill layer.
    val polygonAnnotationOptions: PolygonAnnotationOptions = PolygonAnnotationOptions()
      .withPoints(points)
      // Style the polygon that will be added to the map.
      .withFillColor("#ee4e8b")
      .withFillOpacity(0.4)
    // Add the resulting polygon to the map.
    polygonAnnotationManager.create(polygonAnnotationOptions)

Map with Polygon

I would like to shade the area outside of the polygon and have the area inside the polygon without shading. How do I go about doing this?


Solution

  • You can create a polygon that occupies the whole world and add a hole inside that polygon:

        val points = listOf(
            listOf(
                Point.fromLngLat(-180.0, 90.0),
                Point.fromLngLat(180.0, 90.0),
                Point.fromLngLat(180.0, -90.0),
                Point.fromLngLat(-180.0, -90.0),
                Point.fromLngLat(-180.0, 90.0)
            ),
            listOf(
                Point.fromLngLat(17.94, 59.25),
                Point.fromLngLat(18.18, 59.25),
                Point.fromLngLat(18.18, 59.37),
                Point.fromLngLat(17.94, 59.37),
                Point.fromLngLat(17.94, 59.25)
            )
        )