Mapbox悬停弹出窗口不会关闭

时间:2018-05-17 17:35:59

标签: javascript popup hover mapbox mapbox-gl-js

我已使用popup on hover的另一个示例调整了popup on click的Mapbox示例,除了弹出窗口不会关闭之外,一切都运行良好。鼠标离开&#34 ;.当我把这两个例子结合起来时,我肯定做错了什么,但我无法在任何地方找到答案。请帮忙!



<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

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

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

所以你需要将popup变量的声明移到两个函数的范围内。

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