Reputation: 17
I need from Google Place Autocomplete these values:
alert(
place.name + // Works
place.geometry.location.lat() + // Works
place.country + // Not works - what is correct value to get country value?
place.state // Not works - what is correct value to get state value?
);
It works for place.name and place.geometry, but it not works for place.country and place.state.
How to get also the other two values? Thank you for any advice.
Whole function:
function initializeGoogleMaps() {
var input = document.getElementById("googleMapsSearch");
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(
autocomplete,
"place_changed",
function() {
var place = autocomplete.getPlace();
alert(
place.name + // Works
place.geometry.location.lat() + // Works
place.country + // Not works - what is correct value to get country value?
place.state // Not works - what is correct value to get state value?
);
document.getElementById("city").value = place.name; // Works
document.getElementById("cityLat").value = place.geometry.location.lat(); // Works
document.getElementById("country").value = place.country; // Not works
document.getElementById("state").value = place.state; // Not works
});
}
Upvotes: 0
Views: 503
Reputation: 624
You can get the state and the country under the address_components
array returned by the getDetails()
method. Since the address components is being returned as an array, you can parse the results like this:
var country;
var state;
var components = place.address_components;
for(i=0;i<components.length;i++){
if(place.address_components[i].types[0].toString() === 'administrative_area_level_1'){
state = place.address_components[i].long_name;
}else if(place.address_components[i].types[0].toString() === 'country'){
country = place.address_components[i].long_name;
}
}
Note: administrative_area_level_1
usually signifies to the state
and varies depending on the political heirarchy of a certain country.
Here's a complete sample you can refer to. You just need to replace "YOUR_API_KEY" with your own API key.
For more information regarding Place details results, please checkout this link: https://developers.google.com/maps/documentation/javascript/places#place_details_results
Hope this helps!
Upvotes: 0