Mapbox悬停弹出窗口不会关闭

问题描述 投票:0回答:1

我使用popup on hover的另一个例子改编了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>
javascript popup hover mapbox mapbox-gl-js
1个回答
0
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.