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.
Asked
Active
Viewed 5.0k times
2 Answers
20
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.
IvanSanchez
- 10,206
- 2
- 19
- 35
12
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.
Worm
- 252
- 3
- 8
ramiroaznar
- 4,419
- 2
- 14
- 29
-
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. – DarkKunai99 Sep 09 '16 at 17:37
-
I have not worked with Cesium, maybe Ivan or on the
cesiumtag can give you a better answer. – ramiroaznar Sep 10 '16 at 10:06 -
-
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). – ramiroaznar Sep 10 '16 at 21:57
var latlng = self._map.containerPointToLatLng([event.originalEvent.clientX - vpWidthDifference, event.originalEvent.clientY - vpHeightDifference]);– DarkKunai99 Sep 14 '16 at 16:08