Add an event listener on a Marker in Leaflet

المشرف العام

Administrator
طاقم الإدارة
I am using leaflet in order to render a map. I created a map with markers and i dont know how to implement the Event Listener 'onClick' on each Marker.

My code

var stops = JSON.parse(json); var map = new L.Map('map', { zoom: 12, minZoom: 12, center: L.latLng(41.11714, 16.87187) }); map.addLayer(L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data', maxZoom: 18, id: 'mapbox.streets', accessToken: '-----' })); var markersLayer = new L.LayerGroup(); map.addLayer(markersLayer); //populate map from stops for (var i in stops) { L.marker(L.latLng(stops.Position.Lat, stops.Position.Lon), { title: stops.Description }).addTo(markersLayer).bindPopup("" + stops.Description + "").openPopup(); } Example

map.on('click', function(e) { alert(e.latlng); }); Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:

function onClick(e) { ... } map.on('click', onClick); map.off('click', onClick);

أكثر...
 
أعلى