【问题标题】:Mapbox GL JS : Popup onclick with external JSONMapbox GL JS:带有外部 JSON 的弹出 onclick
【发布时间】:2019-02-14 00:37:52
【问题描述】:

当用户单击多边形时,我试图在 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 的新手,我已经尝试通过这里和各种在线资源来解决这个问题。我希望问题只是我的描述变量设置错误并且我遗漏了一些简单的东西。

【问题讨论】:

  • 为什么不用浏览器内置的调试工具?
  • 对于 setLngLat 函数参数必须指定为 LngLat 实例、对象 {lng: , lat: } 或 [, 的数组]
  • 我不明白这一点。我的技能水平很低。我更容易看到代码来理解发生了什么。
  • 当你点击多边形时 - 你想在哪里显示弹出窗口?
  • 无论是在里面还是在多边形的边缘都是我想要的,无论哪种方式。

标签: geojson mapbox-gl-js


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2017-01-26
    • 2016-06-05
    • 2020-07-17
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多