当用户点击多边形时,我试图在Mapbox GL JS中显示一个弹出窗口(在Flash Flood警告期间它是一个天气警告框)。
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的新手,我已经尝试在这里查看和各种来源在线解决这个问题。我希望问题只是我的描述变量设置错误,我错过了一些简单的东西。
我调试了你提供的代码,发现变量coordinates
包含一个lat-lng数组的对象。
修改该部分应解决问题。
var coordinates = e.features[0].geometry.coordinates[0][0].slice();
在coordinates[0][0]
中,第二个索引确定了弹出窗口的位置。
这是工作代码。 https://jsbin.com/suzapug/1/edit?html,output