-1

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?

user1097772
  • 3,499
  • 15
  • 59
  • 95

1 Answers1

0

Well the first thing i'd check is my order of operations, it could be that the alert is executing BEFORE your geocoder is executing, try running your alert in a console view after the whole javascript runs.

If address is still staying undeclared do this on your line.

window.address = results[1].formatted_address;

this will set address as a window variable, which is the same scope as declaring var address outside of any function.

Jordan
  • 96
  • 1
  • 4