17

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!

21

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

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

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.