LeafletJS - Event Handling



The Leaflet JavaScript program can respond to various events generated by the user. In this chapter, we will provide a few examples demonstrating how to perform event handling while working with Leaflet.

Event Handling

Follow the steps given below to add events to the map.

Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Add the handler to the map, as shown below.

map.on("click", function(e){
   new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
})

Example

The following code demonstrates even handling using Leaflet. When executed, if you click on the map, a marker will be created on that particular location.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Polygons</title>
      <link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
      <script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
   </head>
   
   <body>
      <div id = "map" style = "width: 900px; height: 580px"></div>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 7
         }
         var map = new L.map('map', mapOptions);    // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
         map.addLayer(layer); // Adding layer to the map
         
         map.on("click", function(e){
            new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
         })
      </script>
   </body>
   
</html>

It generates the following output −

Event Handling
Advertisements