单击带有Leaflet和geoJSON的事件


18

如何将click事件附加到geoJSON,然后在单击时执行Ajax函数。我调查了一下,onEachFeature但是它是在加载geoJSON时执行的,而不是在单击时执行的,因此执行了大量的ajax调用!

Answers:


22

您选择的方向正确onEachFeature

只是您必须在每个元素上绑定事件单击。

见下文(经测试)

function whenClicked(e) {
  // e = event
  console.log(e);
  // You can make your ajax call declaration here
  //$.ajax(... 
}

function onEachFeature(feature, layer) {
    //bind click
    layer.on({
        click: whenClicked
    });
}

geojson = L.geoJson(your_data, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

8

您可以用比ThomasG77的版本少一些的代码来做到这一点:

function onEachFeature(feature, layer) {
    //bind click
    layer.on('click', function (e) {
      // e = event
      console.log(e);
      // You can make your ajax call declaration here
      //$.ajax(... 
    });

}

geojson = L.geoJson(your_data, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

3

作为内联函数的另一种方式

geojson = L.geoJson(your_data, {
style: style,
onEachFeature: function onEachFeature(feature, layer) {

layer.on('mouseover', function (e) {
  // e = event
  console.log(e);
  // You can make your ajax call declaration here
  //$.ajax(... 
  });}).addTo(map);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.