Get country from address with the Google Maps API

- 1 answer

Ad

I'm geocoding an address with Google Maps API and I need to get the country name by a given address. This is my code:

var address = "<?php echo $address;?>";
var raw;

function initialize(){

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({
        "address": address
    },function(results){
        raw = results[0].address_components;
        console.log(raw);
    });

}

google.maps.event.addDomListener(window, 'load', initialize);

Console returns an array with data and I want to get the country as seen on the image below:

Here's what the console returns

How can I achieve that? I've tried with:

raw = results[0].address_components.types["country"];

raw = results[0].address_components.types;

raw = results[0].address_components.country;

raw = results[0].address_components.types.long_name;

But all that returns either "undefined" or nothing. I just want to get "Argentina" and store it in a variable.

Ad

Answer

Ad

Since the array of objects is dynamic you'll have to iterate through it:

var raw;
var address = "1 Infinite Loop, Cupertino, CA"

function initialize(){
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({
        "address": address
    },function(results){
        raw = results;
        //find country name
        for (var i=0; i < results[0].address_components.length; i++) {
          for (var j=0; j < results[0].address_components[i].types.length; j++) {
            if (results[0].address_components[i].types[j] == "country") {
              country = results[0].address_components[i];
              console.log(country.long_name)
              console.log(country.short_name)
            }
          }
        }
    });
}

initialize();

Ad
source: stackoverflow.com
Ad