Mapbox悬停弹出窗口不会关闭 [英] Mapbox hover popup won't close

查看:60
本文介绍了Mapbox悬停弹出窗口不会关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将Mapbox示例改编为弹出窗口鼠标悬停上使用另一个示例弹出单击,一切正常,只是弹出窗口不会在"mouseleave"上关闭.当我将两个示例结合在一起时,我一定做错了什么,但我找不到任何答案.请帮忙!

I've adapted the Mapbox example for a popup on hover using another example for a popup on click, and everything is working great except that the popup won't close on "mouseleave". I must have done something wrong when I combined the two examples but I can't find the answer anywhere. Please help!

<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')事件的处理程序中定义.

And, accordingly, it is not defined inside the handler of the map.on('mouseleave') event.

因此,您需要将 popup 变量的声明移至两个函数的作用域.

So you need to move the declarations of the popup variable to the scope of both functions.

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

这篇关于Mapbox悬停弹出窗口不会关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆