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
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);
-
Is there a way to have a global click handler, the same for all features without looping? Commented 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) ?! Commented 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) Commented Mar 4, 2021 at 16:25
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);
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);