Mapbox GL:获取图层 ID

Mapbox GL: Get Layer IDs

我有一个包含几十个图层的地图,每个图层都有一个唯一的 ID。我有用于打开和关闭图层的复选框,为此我需要所有图层 ID 的单个数组。我不知道如何遍历所有地图图层以捕获图层 ID。我尝试使用 map.getLayer() 但此 returns 图层作为对象,而不是图层 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 答案由于未知原因不方便,请使用 map.getStyle().layers 获取对象图层数组,然后将其映射以获取字符串 ID 数组。

var layers = map.getStyle().layers;

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