Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API - geocode() doesn't return lat and long

Tags:

google-maps

I'm trying to get a latitude and longitude by address with the following code:

 function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var address = "HaYarkon 100 TelAviv Israel";
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
       {
            TelAviv = new google.maps.LatLng(results[0].geometry.location.latitude,results[0].geometry.location.longitude);             
       }
    });

    var myOptions = {
        zoom:7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: TelAviv
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
}

The problem is that results[0].geomety.location.latitude and longitude are undefinde.

What I see in the results in the console are the next:

 location: O

   $a: 51.5414691

   ab: -0.11492010000006303

Why does it show $a and ab instead of latitude and longitude

like image 227
Alon Avatar asked May 07 '12 12:05

Alon


Video Answer


2 Answers

Use the following functions instead of directly accessing the properties:

results[0].geometry.location.lat()

and

results[0].geometry.location.lng()

The Google code is obfuscated and internally uses short variable names that can change from one day to another.

like image 96
Matt Handy Avatar answered Oct 07 '22 06:10

Matt Handy


You MUST use

results[0].geometry.location.lat()
results[0].geometry.location.lng()

Using

results[0].geometry.location[0]
results[0].geometry.location[1]

returns undefined.

This was very confusing to me because the API sometimes returned a field named 'ab' and other times it returned 'Za'. Accessing the elements by their semantic value (with .lat and .lng) rather than the exact string name is far safer and more readable.

like image 35
Matt Kneiser Avatar answered Oct 07 '22 06:10

Matt Kneiser