Mapbox GL JS:使用外部JSON弹出onclick

时间:2018-09-09 09:35:18

标签: geojson mapbox-gl-js

当用户单击多边形(这是Flash Flood警告期间的天气警告框)时,我试图在Mapbox GL JS中显示一个弹出的onclick。

I have been using this example from Mapbox as a base和-

This is my JSON file,我正在尝试从中提取数据。

当我单击多边形时,没有弹出窗口。当我将鼠标悬停在上面时,光标会发生变化-因此我知道诸如文件名和目录结构之类的基本问题是正确的。

我的以下代码是从示例中修改的。我正在尝试加载每个多边形的“描述” :(我的地图称为“ topleftmapbox”,JSON ID为“ FFWWarning”)

// When a click event occurs on a feature in the places layer, open a popup at the
    // location of the feature, with description HTML from its properties.
    topleftmapbox.on('click', 'FFWWarning', function (e) {
        var coordinates = e.features[0].geometry.coordinates.slice();
        var description = e.features[0].description;

        // Ensure that if the map is zoomed out such that multiple
        // copies of the feature are visible, the popup appears
        // over the copy being pointed to.
        while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
            coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
        }

        new mapboxgl.Popup()
            .setLngLat(coordinates)
            .setHTML(description)
            .addTo(topleftmapbox);
    });

    // The following code below runs correctly and changes the cursor on mouseover.

    topleftmapbox.on('mouseenter', 'FFWWarning', function () {
        topleftmapbox.getCanvas().style.cursor = 'pointer';
    });

    // Change it back to a pointer when it leaves.
    topleftmapbox.on('mouseleave', 'FFWWarning', function () {
        topleftmapbox.getCanvas().style.cursor = '';
    });

我觉得我的问题在代码的这一部分中:

    var coordinates = e.features[0].geometry.coordinates.slice();
    var description = e.features[0].description;

我对Mapbox还是陌生的,我尝试通过这里和各种在线资源来解决此问题。我希望问题只是我的描述变量设置有误,并且我缺少一些简单的东西。

1 个答案:

答案 0 :(得分:1)

我调试了您提供的代码,发现变量coordinates包含一个具有lat-lng数组的对象。

修改该部分应该可以解决该问题。

var coordinates = e.features[0].geometry.coordinates[0][0].slice();  

coordinates[0][0]中,第二个索引确定弹出窗口的位置。
这是工作代码。 https://jsbin.com/suzapug/1/edit?html,output