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 ?
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: "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With