I am trying to convert the position of the mouse on a google map into a LatLng object. I see quite a few posts on getting the position from with the google map "click" event etc, like this:
google.maps.event.addListener(map, 'click', function(event) {
mouseLocation = event.latLng;
});
But, this doesn't work for my purposes because I am not responding to a map event, I'm responding to a 'tapHold' event. Inside the tapHold event I'd like to get the latitude and longitude of the current mouse position. Actually I could see a function like this being useful in many ways beyond just a tapHold event.
I can think of some hacks like, to create a mouseover event on the fly, then only let it fire once and delete it after getting the LatLng object from the rollover event, but, seems sorta hackish to me... Looking for a more elegant solution. Thanks!
The clientX property returns the horizontal coordinate (according to the client area) of the mouse pointer when a mouse event was triggered. The client area is the current window. Tip: To get the vertical coordinate (according to the client area) of the mouse pointer, use the clientY property.
First, open Google Maps on your computer, right-click the place you want to get coordinates. A pop-up window will show, you can find the latitude and longitude on the top. Left-click and copy them automatically.
google.maps.event.addListener(map, 'mousemove', function (event) {
displayCoordinates(event.latLng);
});
function displayCoordinates(pnt) {
var lat = pnt.lat();
lat = lat.toFixed(4);
var lng = pnt.lng();
lng = lng.toFixed(4);
console.log("Latitude: " + lat + " Longitude: " + lng);
}
Source: http://seydahatipoglu.wordpress.com/2012/10/21/how-to-display-cursor-coordinates-in-google-map-javascript/
There are several function for working with pixels, to use them you need to access the projection first.
From the map object
map.getProjection().fromPointToLatLng(new google.maps.Point(x, y))
From an overlay object:
overlay.getProjection().fromContainerPixelToLatLng(new google.maps.Point(x, y));
You can do this with a dummy overlay as well:
var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
Here is an reference to the documentation: https://developers.google.com/maps/documentation/javascript/reference#Projection
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