function instate(loc)
{
var a;
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow
geocoder.geocode({'location': loc}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(5);
var arrAddress = results[0].address_components;
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "administrative_area_level_1"){
a = address_component.short_name;
console.log(a);
}
//return false; // break the loop
});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
The code above can print out the right value of 'a' in console, but when I put the console.log(a) at the bottom of the function, just like below, it cannot print the right value and just print out "undefined", why is that?
function instate(loc)
{
var a;
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow
geocoder.geocode({'location': loc}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(5);
var arrAddress = results[0].address_components;
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "administrative_area_level_1"){
a = address_component.short_name;
}
//return false; // break the loop
});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
console.log(a);
}