Android Mapbox SDK: Hiding Labels As User Zooms Out

I’m using Mapbox Android SDK in a side project to show bike paths and points of interest (POI). The POIs are indicated with a marker icon and a text label. I only want to show the labels at certain zoom levels. Mapbox provides some label collision options but none of them work like I want. Here’s how I got this working.

Taking a cue from a similar question posted on StackOverflow regarding Mapbox’s Javascript SDK, I am able to change the text size based on zoom level. So by setting text size to 0 for some levels I can effectively hide the text. This gave me a chance to learn about Mapbox’s Expression and Stop classes.

class MapFragment : Fragment()

    private val textSize: Float = 16f
    private val zoomLevelForText: Int = 12

    ...

    // text-sized PropertyValue backed by Expression (i.e. conditional
    // logic) which essentially makes text size 0 at a certain zoom level
    // i.e. hides text label above certain zoom and only shows when user zooms in
    private val textSizePropertyValue: PropertyValue<Expression> = PropertyFactory.textSize(
        interpolate(
            linear(),
            zoom(),
            stop(0, 0),
            stop(zoomLevelForText - 1, 0),
            stop(zoomLevelForText, textSize)
        )
    )

    ...

    // add property when building layers
    style.addLayer(
        SymbolLayer(LAYER_ID, SOURCE_ID)
            .withProperties(
                PropertyFactory.textField(Expression.get(KEY_LABEL)),
                PropertyFactory.iconImage(IMAGE_NAME),
                textSizePropertyValue
                // other properties
            )
    )

This sets the text level to zero for all zoom levels from 0 to 11, then increases text size to “full sized” between zooms 11 and 12, then keeps text “full sized” at zoom level 12 and beyond.

Text size of 16 is my best guess for normal label text before I started mucking with it.

You will have to decide which zoom level makes sense for you; it really depends on how cluttered your map is.