[GIS] Add an event listener on a Marker in Leaflet

javascriptleaflet

I am using Leaflet in order to render a map. I created a map with markers and I don't 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[i].Position.Lat, stops[i].Position.Lon), {
    title: stops[i].Description
  }).addTo(markersLayer).bindPopup("<b>" + stops[i].Description + "</b>").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);

Best Answer

Welcome to GIS Stack Exchange!

There should be no special difficulty in attaching a callback to marker(s) click event. You would simply use myMarker.on('click', callback) like you did with the map. You would also have to do that for every marker you want to attach a callback to.

Another possibility would be to add all your markers into a Feature Group (e.g. simply instantiate your markersLayer with L.featureGroup() instead of L.layerGroup()), so that you can attach the callback directly to that Group. It will receive the click events from individual markers, and you can access the individual clicked feature using event.layer.

var markersLayer = L.featureGroup().addTo(map);

// populate map from stops…

markersLayer.on("click", function (event) {
    var clickedMarker = event.layer;
    // do some stuff…
});

Demo: http://jsfiddle.net/ve2huzxw/74/

Similar question asked by someone else on Leaflet forum: https://groups.google.com/forum/#!topic/leaflet-js/RDTCHuLvMdw