为 Mapbox GL JS 中的每个源和图层添加弹出窗口

Add popup for every source and layer in Mapbox GL JS

我在地图上通过循环生成了多个源和图层,如源代码所示。

var id, lat, lng, point;

function setPosition() {
    $.post('m/getData.php', function(data) {
        var split = data.split(",");
        for (i = 0; i < split.length - 1; i++) {
            var secSplit = split[i].split("|");
            id = secSplit[0];
            lat = secSplit[1];
            lng = secSplit[2];
            point = {
                "type": "Point",
                "coordinates": [lng, lat]
            };
            map.addSource(id, {
                type: 'geojson',
                data: point
            });
            map.addLayer({
                "id": id,
                "type": "symbol",
                "source": id,
                "layout": {
                    "icon-image": "ferry-15"
                }
            });
        }
    });
}

对于我的问题,是否可以使用 Mapbox GL JS 将弹出窗口动态绑定到每个源和图层?

从我在 Mapbox 示例中看到的,它仅显示了如何将弹出窗口与来自单个图层的要素集合绑定,如您所见here

在 Mapbox-GL-JS 中,您实际上并不 "bind popups"。如链接示例所示,您响应鼠标单击,查询鼠标单击处的渲染功能,然后在需要时显示弹出窗口。

可以查询多层吗?是的,如 the documentation points out:

An array of style layer IDs for the query to inspect. Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.

因此,一个简单的方法是维护一个变量,其中包含您添加的所有图层的 ID,然后将其传递给 queryRenderedFeatures()

也可以通过查询map.getStyle().layers得到所有图层ID的列表。