English 中文(简体)
LeafletJS - Event Handling
  • 时间:2024-12-22

LeafletJS - Event Handpng


Previous Page Next Page  

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 handpng while working with Leaflet.

Event Handpng

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

Step 1 − Create a Map object by passing a <span> 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("cpck", function(e){
   new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
})

Example

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

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Polygons</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <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("cpck", function(e){
            new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
         })
      </script>
   </body>
   
</html>

It generates the following output −

Event Handpng Advertisements