27

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!

3 Answers 3

35

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);
3
  • Is there a way to have a global click handler, the same for all features without looping?
    – Eric Burel
    Mar 4, 2021 at 10:21
  • Not aware of it. In the official tutorial, always using this way e.g leafletjs.com/examples/geojson and leafletjs.com/examples/choropleth I suppose you wanted one listener like on an <ul> tag to know about its <li> child(s) ?!
    – ThomasG77
    Mar 4, 2021 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 4, 2021 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);
5

just another way as inline function

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.