Skip to content

Distance Expression

Note

You can find the full source code of this example in DistanceExpressionActivity.kt of the MapLibreAndroidTestApp.

This example shows how you can modify a style to only show certain features within a certain distance to a point. For this the distance expression is used.

Screenshot of map where only labels inside some circular area are shown

Map data OpenStreetMap. © OpenMapTiles.

First we add a fill layer and a GeoJSON source.

val center = Point.fromLngLat(lon, lat)
val circle = TurfTransformation.circle(center, 150.0, TurfConstants.UNIT_METRES)
maplibreMap.setStyle(
    Style.Builder()
        .fromUri(TestStyles.OPENFREEMAP_BRIGHT)
        .withSources(
            GeoJsonSource(
                POINT_ID,
                Point.fromLngLat(lon, lat)
            ),
            GeoJsonSource(CIRCLE_ID, circle)
        )
        .withLayerBelow(
            FillLayer(CIRCLE_ID, CIRCLE_ID)
                .withProperties(
                    fillOpacity(0.5f),
                    fillColor(Color.parseColor("#3bb2d0"))
                ),
            "poi"
        )

Next, we only show features from symbol layers that are less than a certain distance from the point. All symbol layers whose identifier does not start with poi are completely hidden.

for (layer in style.layers) {
    if (layer is SymbolLayer) {
        if (layer.id.startsWith("poi")) {
            layer.setFilter(lt(
                distance(
                    Point.fromLngLat(lon, lat)
                ),
                150
            ))
        } else {
            layer.setProperties(visibility(NONE))
        }
    }
}