Mapbox - 单击时的指针未定义

Mapbox - Pointer on click not defined

我正在尝试在 Mapbox GL JS 中向我的地图图标添加一个弹出窗口。到目前为止,我一直没有成功。

当我创建图层时,我在图层的数据中指定了几个属性。但是,当我尝试向图标添加弹出窗口时,所有属性都不存在。试图简单地访问它们 returns undefined.

添加图层:

function addRedAirports() {
    map.addSource('hoggitRed', {
        type: 'geojson',
        cluster: true,
        clusterMaxZoom: 14, // Max zoom to cluster points on
        clusterRadius: 10, // Radius of each cluster when clustering points (defaults to 50)
        data: redAirportArray[0]
    });
    map.addLayer({
        "id": 'reds',
        "type": "symbol",
        "source": "hoggitRed",
        "layout": {
            "icon-image": "redIcon",
            "icon-size": 0.075,
            "icon-anchor": "bottom",
            "icon-allow-overlap": true
        }
    });

这里是数据的内容(redAirportArray[0])。我正在循环 api 来获取这些数据。

当我将此数据传递给 mapbox 时,属性是完整且正确的。但是,当我尝试访问它们以获取弹出窗口时,我得到了未定义的信息。控制台记录 mapbox 层显示 none 存在的输入属性..

(我稍微压缩了这段代码。每个循环我创建一个特征,然后将其推送到特征集合。为了简单起见,我在这个片段中结合了两者)

let redAirportArray = [{
    "type": "FeatureCollection",
    "features": [{
    "type": "Feature",
    "properties": { //SETTING THE PROPERTIES
        "test": 'test',
        "ID": airportsRed[x].Id,
        "team": airportsRed[x].Coalition
    },
    "geometry": {
        "type": "Point",
        "coordinates": [airportsRed[x].LatLongAlt.Long, airportsRed[x].LatLongAlt.Lat]
    }
}]

点击时添加弹出窗口

map.on('click', 'reds', function (e) {
    var coordinates = e.features[0].geometry.coordinates.slice();
    let team = e.features[0].properties.ID;


    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
    coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }

    new mapboxgl.Popup()
    .setLngLat(coordinates)
    .setHTML(team)
    .addTo(map);
});

在此先致谢,希望您能提供帮助!

根据当前添加图层的方式,您在错误的位置查找 propertiese.features[0] 未定义,因为 e 是您刚刚单击的地图项。您的弹出代码应如下所示:

map.on('click', 'reds', function (e) {
    var coordinates = e.geometry.coordinates.slice(); // Changed
    let team = e.properties.ID; // Changed


    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
    coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }

    new mapboxgl.Popup()
    .setLngLat(coordinates)
    .setHTML(team)
    .addTo(map);
});