Get latitude and longitude from static google map

2019-02-14 21:22发布

问题:

I want to display a static map and on mouse over the map get latitude and longitude on mouse over the map

回答1:

It needs some calculations, you'll find the required methods in the source of this demo: https://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1

function that implements these calculations for usage with a static map:

function FX(lat,//center-latitude of the static-map
            lng,//center-longitude of the static-map
            zoom,//zoom of the static-map
            width,//width of the static-map
            height,//height of the static-map
            mouseX,//x-coordinate of the mouseevent inside the element
            mouseY//y-coordinate of the mouseevent inside the element
            ){


   var x = mouseX-(width/2),
       y = mouseY-(height/2),
       s = Math.min(Math.max(Math.sin(lat * (Math.PI / 180)), -.9999), .9999),
       tiles = 1 << zoom,
       centerPoint={
                    x: 128 + lng * (256/ 360),
                    y: 128 + 0.5 * Math.log((1 + s) / (1 - s)) 
                       *-(256 / (2 * Math.PI))
                   },
       mousePoint={
                    x:(centerPoint.x*tiles)+x,
                    y:(centerPoint.y*tiles)+y
                  },
       mouseLatLng={
                    lat:(2 * Math.atan(Math.exp(((mousePoint.y/tiles) - 128) 
                                        / -(256/ (2 * Math.PI)))) -
                            Math.PI / 2)/ (Math.PI / 180),
                    lng:(((mousePoint.x/tiles) - 128) / (256 / 360))
                   };

      return mouseLatLng;

    }

Demo: http://jsfiddle.net/doktormolle/yxf2C/show/