javascriptmapboxmapbox-gl-js

How to toggle the display of labels on a Mapbox map?


I have created my own Mapbox style using the Mapbox Studio.

This GL JS map itself is imported in the code like this:

let selectedStyle = "mapbox://styles/abc/def";

map = new mapboxgl.Map({
    container: 'map',
    center: [parseFloat(lonInput), parseFloat(latInput)],
    zoom: parseFloat(zoomInput),
    pitch: 0,
    style: selectedStyle,
    preserveDrawingBuffer: true,
    fadeDuration: 0,
    attributionControl: false,
    zoomControl: false
});

I have added an input checkbox that should make it possible for the visitors to toggle the display of the labels on the map. Based on their choice all the names of the cities, streets, POIs, ... should or should not be shown on the map.

After some research, I have found this page on the documentation of Mapbox: https://docs.mapbox.com/mapbox-gl-js/guides/styles/#mapbox-standard-1

I think it should be possible to toggle the display of the labels with the following code:

map.on('style.load', () => {
  map.setConfigProperty('basemap', 'showPlaceLabels', false);
});

But I am not sure what the baseMap refers to. It seems like I do not have it in my application. What should it be?

Or is there another way to do this?


Solution

  • basemap refers to the core Mapbox Standard style which is enabled by default when no style option is provided.

    Since you are using your own style, you need to do something like this

    map.style.stylesheet.layers.forEach(function(layer) {
        if (layer.type === 'symbol') {
            map.setLayoutProperty(layer.id, "visibility", "none");
        }
    });