【问题标题】:Mapbox hover popup won't closeMapbox悬停弹出窗口不会关闭
【发布时间】:2018-05-17 17:35:59
【问题描述】:

我已经为popup on hover 调整了 Mapbox 示例,并为popup on click 使用了另一个示例,除了弹出窗口不会在“鼠标离开”时关闭之外,一切都运行良好。当我结合这两个例子时,我一定做错了,但我在任何地方都找不到答案。请帮忙!

<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】:

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

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

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

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

    【讨论】:

    • 非常感谢,这非常有效,正是我需要的答案!我实际上意识到,当您停止将鼠标悬停在该点上时,我不希望弹出窗口消失,因为这样人们就无法单击弹出窗口中的“了解更多”链接,但是您的回答绝对正确,并且会有所帮助未来的我。谢谢!
    • 感谢 JS Fiddle,这帮助我了解了如何打开/关闭弹出窗口
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多