Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 705
yarek Avatar asked Dec 11 '22 13:12

yarek


1 Answers

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: "";
like image 79
xomena Avatar answered Dec 27 '22 07:12

xomena