yarek
yarek

Reputation: 12034

How to get country from google maps api?

I use this script:

var place = autocomplete.getPlace();
latitude = place.geometry.location.lat();
longitude = place.geometry.location.lng();

street_number = place.address_components[0].long_name;
route = place.address_components[1].long_name;
locality = place.address_components[2].long_name;
administrative_area_level_1 = place.address_components[3].long_name;
country = place.address_components[5].long_name;
postal_code = place.address_components[6].long_name;

Which works fine when user types in full address. But when user types in ONLY city or city, then country value is not in place.address_components[5] but in place.address_components[2] :

How to know what field fits the index of the returned array ?

Upvotes: 4

Views: 8778

Answers (2)

Enzo Barrera
Enzo Barrera

Reputation: 455

You should try to look at the "types" property inside the response of getPlace() not just to get the country, you can also get more information about a place for example:

function onPlaceChanged() {

    let country, city, area;

    if (autocomplete != null) {
        const place = autocomplete.getPlace();
        
        for (var i = 0; i < place.address_components.length; i++) {
            for (var j = 0; j < place.address_components[i].types.length; j++) {
                if (place.address_components[i].types[j] === "country") {
                    country = place.address_components[i].short_name;
                }
                if (place.address_components[i].types[j] === "locality") {
                    city = place.address_components[i].long_name;
                }
                if (place.address_components[i].types[j] === "administrative_area_level_1") {
                    area = place.address_components[i].long_name;
                }
            }
        }
        const formattedAddress = place.formatted_address;

        console.log(`Country: ${country}`);
        console.log(`City: ${city}`);
        console.log(`Area: ${area}`);
        console.log(`Formatted Address: ${formattedAddress}`);
    } else {
        // Write some code here to handle error when autocomplete is null
    }
}

Note that here we're geting the country "short_name" which is the country code, of course you can get the complete country name with "long_name".

Hope it's useful 🙂

Upvotes: 0

xomena
xomena

Reputation: 32100

You shouldn't rely on index of element in place.address_components array. Instead you have to analyze the "types" field to find the corresponding address component for the country.

It can be done with Array.prototype.filter() and Array.prototype.includes() functions.

var filtered_array = place.address_components.filter(function(address_component){
    return address_component.types.includes("country");
}); 
var country = filtered_array.length ? filtered_array[0].long_name: "";

Upvotes: 13

Related Questions