[GIS] Using Leaflet Js, is it possible to know the onclick location of a Marker (ignore anchor point)

coordinatesleafletmarkers

I have a marker object that is of a specific height and width, and although it is pointing a single coordinate, the visual representation of the marker spans many pixels. When I click on the visual representation of the marker, I would like to get the underlying map coordinates, but instead I only have access to the single lat/lng coordinate associated with the marker.

Best Answer

On one hand: whenever Leaflet handles a mouse (or touch) event, you can access the original DOM event in the originalEvent property of the event.

On the other hand: Given a mouse (or touch) DOM event, Leaflet can magically translate its clientX and clientY properties into an instance of L.LatLng by using map.mouseEventToLatLng().

Combine these two things together, and you can have something like:

marker.on('click', function(ev){
  var latlng = map.mouseEventToLatLng(ev.originalEvent);
  console.log(latlng.lat + ', ' + latlng.lng);
});

Check Leaflet's documentation for the other conversion methods, as they might prove useful.