简体   繁体   中英

How to get current latitude and longitude from Google map

I have some problem to get lat/lng from google map in my application.
When I put in alert message 'lat()' or 'lng()' map is not rendered at all.
In the code that I put bellow on map click I get alert with 'undefined' message.
I want to store lat and lng in text field on page when user move map (here I try with click) but something doesn't work here?

function initialize() {
        var latlng = new google.maps.LatLng(44.012, 20.921);
        var myOptions = {
            zoom: 13,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        google.maps.event.addListener(map, "click", function (latlng) {
            if (latlng) {
                alert(latlng.lat);
            }
        });
    }

latlng should be in the event object passed in. So, in order to extract it, you would do something like this:

google.maps.event.addDomListener(map, 'click', function(event) {
    var myLatLng = event.latLng;
    var lat = myLatLng.lat();
    var lng = myLatLng.lng();
    alert( 'lat '+ lat + ' lng ' + lng ); 

}

You can also get lat and lng by the instance of google map:

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); // map instance

google.maps.event.addListener(map, "click", function () {
    var lat = map.data.map.center.lat();
    var lng = map.data.map.center.lng();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM