1110
1110

Reputation: 6829

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);
            }
        });
    }

Upvotes: 2

Views: 9192

Answers (2)

iamawebgeek
iamawebgeek

Reputation: 2865

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();
});

Upvotes: 0

aziz punjani
aziz punjani

Reputation: 25776

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 ); 

}

Upvotes: 1

Related Questions