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!
Asked
Active
Viewed 4.6k times
30
ThomasG77
- 30,725
- 1
- 53
- 93
RustyShackleford
- 717
- 1
- 6
- 19
3 Answers
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
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);
<ul>tag to know about its<li>child(s) ?! – ThomasG77 Mar 04 '21 at 13:06onclickcallback 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