below this text there is code what I tryed.
I want to achive this: outside function geocoder.geocode there is variable called var address. geocoder.geocode ... gets addres from latlng, and I want to set the address by this row address = results[1].formatted_address;
but the varriable address is probably not visible outside.
When I call: alert('Inside: '+ address)
address is correctly set,
but whe I call same outside the function alert ('Outside address: '+address)
the address is back empty string, so setting the address is probably only local, what I want to achieve is to set it outside the function to be able work with this wariable. What do I wrong?
var geocoder = new google.maps.Geocoder();
var myPosition = new google.maps.LatLng(41.850033, -87.6500523);
var address = "";
//get address
geocoder.geocode({'latLng': myPosition}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
address = results[1].formatted_address;
alert('Inside: '+ address);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
alert ('Outside address: '+address);
Edit:
It turned out that it's problem of assynchronous comunication. The outside alert is executed before the the geocoder.geocode is executed. So can I somehow stop executing the script till it will be executed? Synchronize it somehow, to be able work with this variable?