I have a JSON: http://maps.googleapis.com/maps/api/geocode/json?latlng=49,19&sensor=false
and I need get only short_name of country. (For this example 'SK'). Therefore I get the short_name which the attribute "types" contains [ "country", "political" ].
I have...
data.results[0].address_components
thanks.
This will loop through the address components and look for the country type then political. If you only want the country to be returned if both appear then let me know. Although its not hard to modify this code as the main helping point was the for
loop.
// extract country short name (e.g. GB for Great Britain) from google geocode API result
function getCountry(addrComponents) {
for (var i = 0; i < addrComponents.length; i++) {
if (addrComponents[i].types[0] == "country") {
return addrComponents[i].short_name;
}
if (addrComponents[i].types.length == 2) {
if (addrComponents[i].types[0] == "political") {
return addrComponents[i].short_name;
}
}
}
return false;
}
console.log(getCountry(data.results[0].address_components));