- LeafletJS - Controls
- LeafletJS - Overlays
- LeafletJS - Event Handling
- LeafletJS - Layers Group
- LeafletJS - Multi Polyline & Polygon
- LeafletJS - Vector Layers
- LeafletJS - Markers
- LeafletJS - Getting Started
- LeafletJS - Home
LeafletJS Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
LeafletJS - Event Handpng
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 −
Advertisements