Mapbox 悬停弹出窗口不会关闭

Mapbox hover popup won't close

我已经为 popup on hover using another example for a popup on click 改编了 Mapbox 示例,除了弹出窗口不会在 "mouseleave" 上关闭外,一切都运行良好。当我结合这两个例子时,我一定做错了什么,但我无法在任何地方找到答案。请帮忙!

<html>
  <body>
    <div id='map'></div>
    <script>
    mapboxgl.accessToken = 'pk.eyJ1IjoibWFyeXNoYWZmZXIiLCJhIjoiY2poNnkwZ3pvMDI5ZzJ4cWUyY296NnNjdCJ9.PgJCuPhDYgm8oCmsZlAeQA'; // replace this with your access token
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/maryshaffer/cjh6yf7c30apg2sotfzmyf2je', // replace this with your style URL
    });
      
    // code from the next step will go here
  map.addControl(new mapboxgl.NavigationControl());
 
  map.on('mouseenter', 'pilgrimage-sites-markers', function(e) {
        // Change the cursor style as a UI indicator.
        map.getCanvas().style.cursor = 'pointer';
    });
  
  map.on('mouseenter', 'pilgrimage-sites-markers', function(e) {
  var features = map.queryRenderedFeatures(e.point, {
    layers: ['pilgrimage-sites-markers'] // replace this with the name of the layer
  });

  if (!features.length) {
    return;
  }

  var feature = features[0];

  var popup = new mapboxgl.Popup({
    closeOnClick: false,
    offset: [0, -15] })
    .setLngLat(feature.geometry.coordinates)
    .setHTML('<h3>' + feature.properties.title + '</h3><p>' + feature.properties.description + '</p><h4><a href=\"' + feature.properties.link + '\">Learn More</a></h4>')
    .setLngLat(feature.geometry.coordinates)
    .addTo(map);
});  
      
 map.on('mouseleave', 'pilgrimage-sites-markers', function() {
        map.getCanvas().style.cursor = '';
        popup.remove();
  });
      
  </script>
  </body>
</html>

问题是 popup 变量是在 map.on('mouseenter') 事件的处理程序中本地声明的。

因此,它没有在 map.on('mouseleave') 事件的处理程序中定义。

因此您需要将 popup 变量的声明移动到两个函数的范围内。

例如:https://jsfiddle.net/e5j10x1o/