LeafletJS:在缩放结束时触发弹出窗口以显示单击特征的详细信息

时间:2017-07-03 11:06:47

标签: javascript events popup leaflet

单击某个功能时,我正在使用这样的弹出窗口。基本上它会缩放并显示包含功能详细信息的弹出窗口:

    function ClickPopup(e) {    
        var layer = e.target;
        name = e.target.feature.properties.name;
        var main_popup = L.popup()
        .setLatLng(e.latlng())
        .setContent('<span class="big-text">'+name+'</span>')
        .openOn(map);
    }  

  function zoomToFeature(e) {
      map.fitBounds(e.target.getBounds());
      ClickPopup(e);
  } 

    function onEachFeature(feature, layer) {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight,
            click: zoomToFeature,
        });  
   }

它或多或少有效,因为弹出窗口过快(即在缩放结束之前),因此弹出窗口很快就会被放置。 所以我想在缩放结束时使用“zoomend”事件获取弹出窗口:

map.on('zoomend',function(e){ console.log("Zoom End"); });

我的问题是我无法获取/检索/传递从此地图事件(e.target.feature)点击的图层和功能,以显示他的详细信息。

有谁知道如何解决这个问题? 谢谢, 吨。

1 个答案:

答案 0 :(得分:0)

您可以将上下文/范围传递给传单事件。这里没有传递上下文:

function onMapMoveEnd () {
    console.log(this); // this === map
}

function onLayerClick () {
    console.log(this); // this === layer
    map.once('moveend', onMapMoveEnd);
    map.fitBounds(this.getBounds());
}

function onEachFeature (feature, layer) {
    layer.on('click', onLayerClick);
}

现在将图层上下文传递给地图的moveend事件处理程序:

function onMapMoveEnd () {
    console.log(this); // this === layer
}

function onLayerClick () {
    console.log(this); // this === layer
    map.once('moveend', onMapMoveEnd, this); // passing context
    map.fitBounds(this.getBounds());
}

所以现在你可以在moveend处理程序中使用this因为它引用了图层。这是一个完整的例子:

var map = new L.Map('leaflet', {
    center: [0, 0],
    zoom: 0,
    layers: [
        new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
        })
    ]
});

var feature = {
    type: 'Feature',
    properties: {
        property: 'value'
    },
    geometry: {
        type: 'Polygon',
        coordinates: [[[-30, 30], [30, 30], [30, -30], [-30, -30]]]
    }
};

function onMapMoveEnd () {
    this.bindPopup(this.feature.properties.property).openPopup();
}

function onLayerClick () {
    map.once('moveend', onMapMoveEnd, this);
    map.fitBounds(this.getBounds());
}

function onEachFeature (feature, layer) {
    layer.on('click', onLayerClick);
}

new L.GeoJSON(feature, {
    onEachFeature: onEachFeature
}).addTo(map);
body {
    margin: 0;
}

html, body, #leaflet {
    height: 100%;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Leaflet 1.0.3</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link type="text/css" rel="stylesheet" href="//unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
  </head>
  <body>
    <div id="leaflet"></div>
    <script type="application/javascript" src="//unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
  </body>
</html>