Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get map latitude longitude from mouse position

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!

like image 231
botbot Avatar asked Dec 21 '12 04:12

botbot


People also ask

How do I find my mouse pointer coordinates?

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.

How do I extract coordinates from a map?

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.


2 Answers

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/

like image 177
bicycle Avatar answered Oct 10 '22 02:10

bicycle


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

like image 33
Nils Avatar answered Oct 10 '22 03:10

Nils