Mapbox GL:获取图层ID

Mapbox GL:获取图层ID,mapbox,mapbox-gl-js,mapbox-gl,Mapbox,Mapbox Gl Js,Mapbox Gl,我有一个有几十个图层的地图,每个图层都有一个唯一的ID。我有复选框来打开和关闭图层,我需要一个包含所有图层ID的数组。我不知道如何在所有地图图层之间循环以捕获图层ID。我尝试使用map.getLayer,但这会将层作为对象返回,而不是将层ID作为字符串返回。我想遍历所有地图图层,并将图层ID字符串推送到一个新数组中。我该怎么做 mapboxgl.accessToken = "myaccesstoken"; var map = new mapboxgl.Map({ container: "map

我有一个有几十个图层的地图,每个图层都有一个唯一的ID。我有复选框来打开和关闭图层,我需要一个包含所有图层ID的数组。我不知道如何在所有地图图层之间循环以捕获图层ID。我尝试使用map.getLayer,但这会将层作为对象返回,而不是将层ID作为字符串返回。我想遍历所有地图图层,并将图层ID字符串推送到一个新数组中。我该怎么做

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"]

} 

添加图层时,您具有图层ID;然后您可以保存它们:

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);

如果由于未知原因kielni answer不方便,请使用map.getStyle.layers获取对象层数组,然后将其映射为字符串ID数组

var layers = map.getStyle().layers;

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

是否有任何方法可以从所选要素获取图层id?