Reputation: 12487
This is my working code: http://jsfiddle.net/spadez/5ntLetey/1/
It works perfectly but I'm trying to pull the remaining information into the fields. This is the code I had previously for the lat and long that I found online:
lat.val(results[0].geometry.location.lat());
lng.val(results[0].geometry.location.lng());
How can I pull the remaining information in? This is one example of what I tried and didn't work:
country_short.val(results[0].address_components.country());
Here is the API documentation, what am I doing wrong?
Upvotes: 1
Views: 101
Reputation: 8954
You're not doing anything particularly wrong, unfortunately the returned address components can vastly differ. For example if you were to geocode a coordinate set which might be in the middle of an ocean, you;'re not going to get many address
components and perhaps nothing at all, whereas in the middle of somewhere like New York City there are many components that get returned.
What you need to do is to parse the returned response to find something you want like country
and only insert that into your fields if and only if there is an address component that has a type
of "country".
So for example to get country short and long you would do something like this:
// Get Country value.
var country = getCountry(results[0].address_components)
$('#country_long').val(country.long);
$('#country_short').val(country.short);
calling the function which looks something like this:
function getCountry(addressComponents) {
var returnCountry = {
'long': 'N/A',
'short': 'N/A'
};
// Loop through all address components and find country if possible.
$(addressComponents).each(function (componentIndex, component) {
// loop through all "types" of each component to find if there is a type of "country"
$(component.types).each(function (indexTypes, type) {
if (type == 'country') {
// Then return the long_name and short_name of the component
returnCountry.long = component.long_name;
returnCountry.short = component.short_name;
}
});
});
return returnCountry;
}
Demo: http://jsfiddle.net/5ntLetey/3/
Upvotes: 1