15

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.

2 Answers 2

17

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.

1
  • Thanks, that did the trick. I was calculating the latlng based on the pixel count like such: var latlng = self._map.containerPointToLatLng([event.originalEvent.clientX - vpWidthDifference, event.originalEvent.clientY - vpHeightDifference]); Sep 14, 2016 at 16:08
11

You always can retrieve the coordinates from the Leaflet object map. You can use something like this:

map.on('click', function(e){
  var coord = e.latlng;
  var lat = coord.lat;
  var lng = coord.lng;
  console.log("You clicked the map at latitude: " + lat + " and longitude: " + lng);
  });

Here you have a working example.

4
  • Hmm, it's odd because I'm running on Cesium v1.25, and whenever I click on the marker, the event object always contains the latlng of the marker anchor point, not the actual coordinate of the map as in your example. Sep 9, 2016 at 17:37
  • I have not worked with Cesium, maybe Ivan or on the cesium tag can give you a better answer. Sep 10, 2016 at 10:06
  • I apologize, I meant to say Leaflet (latest v1.0 rc) Sep 10, 2016 at 19:02
  • Have a look at the answer given by Ivan, it will solve your problem. Mine as you said is using a very old Leaflet version (I do not know from where I copy that). Sep 10, 2016 at 21:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.