2
votes

I have a map with a few dozen layers, each with a unique ID. I have checkboxes to turn the layers on and off, for which I need a single array of all the layer IDs. I can't figure out how to loop through all of the map layers to capture the layer IDs. I tried using map.getLayer() but this returns the layer as an object, not the layer ID as a string. I want to loop through all of the map layers and push the layer ID strings to a new array. How do I do this?

mapboxgl.accessToken = "myaccesstoken";

var map = new mapboxgl.Map({
container: "map", 
style: "mapbox://styles/mymapboxstyle",  
center: [-71.0664, 42.358],  
minZoom: 14 //  
}); 

map.on("style.load", function () {

map.addSource("contours", {
    type: "vector",
    url: "mapbox://mapbox.mapbox-terrain-v2"
    });

map.addSource("hDistricts-2017", {
    "type": "vector",
    "url": "mapbox://mysource"
    });

map.addLayer({
    "id": "contours",
    "type": "line",
    "source": "contours",
    "source-layer": "contour",
    "layout": {
        "visibility": "none",
        "line-join": "round",
        "line-cap": "round"
        },
    "paint": {
        "line-color": "#877b59",
        "line-width": 1
        }
     });  

map.addLayer({
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13], 
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    }); 

});

var layerIds = [];

function getIds() {

  //here I need to iterate through map layers to get id strings.
  //how do I do this???

 layerIds.push(    ); //then push those ids to new array.

 console.log(layerIds); //["contours", "Back Bay Architectural District"]

} 
2

2 Answers

5
votes

If kielni answer isn't convenient because of unknown reason, use map.getStyle().layers to get an array of object layers then map it to get an array of string ids.

var layers = map.getStyle().layers;

var layerIds = layers.map(function (layer) {
    return layer.id;
});
0
votes

You have the layer ids when you add the layer; you can save them then:

function addLayer(map, options, layerIds) {
    map.addLayer(options);
    layerIds.push(options.id);
}

addLayer(map, {
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13], 
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    },
    layerIds);