首页 > 解决方案 > 当地图处于最大缩放时,地图框弹出位置错误(多个世界副本可见)

问题描述

我有一个 Mapbox 地图的问题,当地图缩小时,附加到标记的弹出窗口显示错误的位置,因此我们看到多个世界副本。请参阅下面的示例。当地图放大并且只有一个世界可见时,弹出窗口会显示在正确的位置。

在此处输入图像描述

这是用于添加标记+弹出窗口并显示它们的代码的简化版本:

 // Add markers to the map
features.forEach(function (marker: any, i: number) {

const popUpContent = '<div>Sample</div>'

// Create the popup
const popup = new mapboxgl.Popup({ offset: 25 })
  .setHTML(popUpContent)
  .on('open', function (event: any) {
    const activePoi = document.getElementsByClassName(poiId)[0]
    activePoi.classList.add('active')
  })
  .on('close', function () {
    const activePoi = document.getElementsByClassName(poiId)[0]
    if (activePoi) {
      activePoi.classList.remove('active')
    }
  })

let mark = new mapboxgl.Marker(markerElement)
  .setLngLat(marker.geometry.coordinates)
  .setPopup(popup)
  .addTo(map)
})

问题

我该如何解决这个问题,以便弹出窗口正确显示在它们各自的标记上方,即使多个世界副本可见?

标签: javascriptmapboxmapbox-gl-js

解决方案


您可以使用 Mapbox 的解决方案:https ://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/

// 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.
map.on('click', 'places', function(e) {

    var coordinates = e.features[0].geometry.coordinates.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);
    });

    // ...

}

推荐阅读