Event Handling ใน LeafletJS

Event handling in LeafletJS allows you to respond to user interactions with the map. For example, you can use event handling to write code that will be executed when the user clicks on the map, zooms in or out, or moves the map.

To handle events in LeafletJS, you need to register an event listener with the map object. You can do this using the on() method. For example, the following code registers an event listener for the click event:

1
2
3
map.on('click', function(event) {
// Do something when the user clicks on the map.
});

The event object that is passed to the event handler contains information about the event that occurred. For example, the event.latlng property contains the latitude and longitude of the point where the user clicked on the map.

You can also register event listeners with individual layers. For example, the following code registers an event listener for the click event on a marker layer:

1
2
3
4
var marker = L.marker([51.505, -0.09]);
marker.on('click', function(event) {
// Do something when the user clicks on the marker.
});

LeafletJS supports a wide variety of events. You can find a list of all supported events in the LeafletJS documentation.

Here are some examples of how event handling can be used in LeafletJS:

  • A map of restaurants with a popup that displays the restaurant’s information when the user clicks on the marker.
  • A map of hiking trails with a line that shows the user’s current location when the user moves the map.
  • A map of a city with a search bar that allows the user to search for points of interest and zoom to the selected point of interest when the user clicks on the search button.

Event handling is a powerful tool that can be used to create interactive and informative Leaflet maps. By learning how to use event handling, you can create maps that are more engaging and useful for your users.