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/