30

How do I attach a click event to a GeoJSON that then executes an Ajax function when clicked. I looked into onEachFeature but that executes when the GeoJSON is loaded, not when clicked, thus executing a ton of ajax calls!

ThomasG77
  • 30,725
  • 1
  • 53
  • 93
RustyShackleford
  • 717
  • 1
  • 6
  • 19

3 Answers3

37

You were on the right way with onEachFeature.

It's just you have to bind event click on each element.

See below (tested)

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);
ThomasG77
  • 30,725
  • 1
  • 53
  • 93
  • Is there a way to have a global click handler, the same for all features without looping? – Eric Burel Mar 04 '21 at 10:21
  • Not aware of it. In the official tutorial, always using this way e.g https://leafletjs.com/examples/geojson/ and https://leafletjs.com/examples/choropleth/ I suppose you wanted one listener like on an <ul> tag to know about its <li> child(s) ?! – ThomasG77 Mar 04 '21 at 13:06
  • Yep, in React I've ended up adding an onclick callback on the GeoJSON, so that clicking on any feature triggers a callback. But for styles for example it doesn't seem to exist, you can't have the same color for all feature without applying a function to each feature (and maybe that makes sense technically, I just don't know) – Eric Burel Mar 04 '21 at 16:25
12

You can do it with slightly less code than ThomasG77's version:

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);
Steve Bennett
  • 5,682
  • 2
  • 44
  • 69
6

Just another way as an inline function:

geojson = L.geoJson(your_data, {
  style: style,
  onEachFeature: function onEachFeature(feature, layer) {
layer.on('mouseover', function (event) {
  console.log(event);
  // You can make your Ajax call declaration here
  //$.ajax(... 
});

}).addTo(map);

Inan
  • 103
  • 4
hoogw
  • 1,712
  • 1
  • 18
  • 23