首页 > 解决方案 > 在地理编码搜索结果后添加弹出窗口

问题描述

我一直在研究如何在 geocding 搜索结果后添加弹出窗口。目前,我正在使用以下文档进行尝试。在文档中,它只显示了如何使用您自己的数据集进行搜索,并且在搜索完成时会出现标记。

但是,我想在单击标记时添加弹出窗口。

我已经阅读了有关“弹出”的 Mapbox 的其他文档。但是,我似乎无法在此代码中实现。

这是我目前正在尝试进行地理编码的文档:https ://docs.mapbox.com/mapbox-gl-js/example/forward-geocode-custom-data/

标签: popupmapboxgeocoding

解决方案


欢迎!我很久以前就遇到过这个问题。我有多边形,我需要一个弹出窗口才能在点击时出现。我的多边形是危险海洋所在的海洋区域(对船只的警告等)。在这里,我有一个激活 onclick 的功能。然后它确保弹出窗口以正确的顺序出现在屏幕上,并且可以选择更改鼠标光标的样式。

我会更详细地解释,但我认为代码在很大程度上是不言自明的。有时很难在文档中找到好的示例(尽管 Mapbox 最近在文档方面取得了长足的进步。)

检查下面的解决方案,如果它适合您,请随时接受它,否则如果您需要,我也可以帮助您解决问题。我已经为你评论了。

map.on('click', 'HazardousSeasWarning', function (e) {
var coordinates = e.features[0].geometry.coordinates[0][0].slice();  
var description = e.features[0].properties.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(map);
});

// Change the cursor to a pointer when the mouse is over the places layer.
map.on('mouseenter', 'HazardousSeasWarning', function () {
    map.getCanvas().style.cursor = 'pointer';
});

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

推荐阅读