I'm trying to get x,y coordinates on mouse move. And I'm getting error when I trying to get it.
TypeError: Cannot read property 'latlng' of undefined at mouseMove (dashboard:593) at HTMLDivElement.onmousemove (dashboard:442)
<div id="map" onmousemove="mouseMove()"></div>
<script type="text/javascript">
var iMaxZoom = 1;
var map = L.map('map', {
crs: L.CRS.Simple,
minZoom: -5,
maxZoom: 1
});
var bounds = [[0,0], [711,473]];
var image = L.imageOverlay('{!! asset('assets/images/birlikmarket.png') !!}', bounds).addTo(map);
map.fitBounds(bounds);
// mouse move detect x, y coordinates
function mouseMove(e) {
var tileSize = [711,473]
try {
console.log(e.latlng)
}catch(error) {
console.log(error)
}
}
</script>
Getting the LatLng of the mouse when a given event such as mouseMove occurs in Leaflet
An issue with your approach is that you are adding an event listener to a native dom event. Instead add a listener to a custom leaflet mouse event which will give you access to latLng.
The first argument of map.on is the event name. The second argument is the callback function to call when the event occurs. The arg passed to this callback function "e" is the object representing the leaflet event. One of the properties on this event is latlng.
Put the following within your script tags:
map.on('mousemove', function(e) {
alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng)
});
"mousemove" refers to a Leaflet mouse event. Leaflet events contain information such as LatLng that won't be present on native DOM events such as "onmousemove".
Additionally you can access other properties of the mouse event such as the pixel coordinates on the map where the event occurred. For more info see this.
Remember that you could just as easily change this event to "click" and only alert the lat lng coordinates when the user clicks on the map.
See this working example: http://jsfiddle.net/LnzN2/684/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With