Event Handlers in Leaflet.js Maps
In the previous article, we have looked at adding shapes to our map application. In this section, we are going to learn about events.
Let's get started
Since Leaflet.js is a Javascript library, it contains event handlers too.
Click Event
Whenever the user interacts with the map, depending upon the nature of the event, a callback function is triggered which handles the event.
Let's see an example for a click event.
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}
map.on('click', onMapClick);
The first argument of an event handler will always be an event object indicating the nature of the event and the second argument will be the callback function.
The click event is handled by the onMapClick function which will alert the users about the latitude and longitude at the location of the click.
Popup
Let's add Popup to our click event handler instead of a plain alert function. The following code serves as a simple starting point.
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
map.on('click', onMapClick);
Observe that the click event now shows a popup.
That's it Folks. You now know how to add event handler to a Leaflet.js map application.