在 MapBox GL JS 中,如何防止弹出标签在我不想看到它们时不断显示?



我用MapBox GL JS做了一个应用程序。我在世界各地都有很多标记。当鼠标光标悬停在它们上面时,我会让它们弹出一个带有描述的框。这通常是我想要的,但当放大/缩小并在地图上移动时,我经常看到这些标签在鼠标光标移动时显示和隐藏时闪烁。这很烦人。

我正试图找到一种好而简单的方法来防止这种情况的发生,也许在这种情况发生之前,需要在标记上悬停几毫秒。或者可能通过使用某种内置的";鼠标光标是静止的还是四处移动;旗帜我不想要求我点击标签,因为这很快就会变得更加烦人。

我目前使用这个代码:

map.on('mouseenter', layerId, (e) =>
{
map.getCanvas().style.cursor = 'pointer';
const coordinates = e.features[0].geometry.coordinates.slice();
const description = e.features[0].properties.description;
const name = e.features[0].properties.name;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) { coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360; }
popup.setLngLat(coordinates).setHTML(name).addTo(map);
});
map.on('mouseleave', layerId, () =>
{
map.getCanvas().style.cursor = '';
popup.remove();
});

这一定是一个常见的问题。你知道,或者你能想出一些不烦人的方法来解决这个问题吗?如果我必须将光标悬停在标签上方以显示它,我可能还需要点击一下。但这已经被取消资格了。另外,我已经将点击事件用于不同的事情("打开相关URL"(。

在'mouseenter'监听器中取消调用回调函数。

阅读更多关于Javascript中的debouncing函数的信息。

您可以在弹出处理程序中检查地图的移动状态函数。有.isZooming((、isMoving((和.isRotating((,您可以从e.target.在处理程序中访问它们

我在我打开的一个项目上快速测试了这一点,它很有效。

map.on('mouseenter', layerId, (e) =>
{
if (!
(
e.target.isZooming() ||
e.target.isMoving() ||
e.target.isRotating() 
) 
)
{
map.getCanvas().style.cursor = 'pointer';
const coordinates = e.features[0].geometry.coordinates.slice();
const description = e.features[0].properties.description;
const name = e.features[0].properties.name;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) { coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360; }
popup.setLngLat(coordinates).setHTML(name).addTo(map);
}
});

相关内容

最新更新