Mapbox GL:获取图层ID

时间:2017-11-13 15:16:09

标签: mapbox mapbox-gl-js mapbox-gl

我有一张有几十个图层的地图,每个图层都有一个唯一的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"]

} 

2 个答案:

答案 0 :(得分:2)

如果由于未知原因导致kielni回答不方便,请使用map.getStyle().layers获取对象图层数组,然后将其映射以获取字符串ID数组。

var layers = map.getStyle().layers;

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

答案 1 :(得分:0)

添加图层时,您有图层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);