0

I've been working a small javascript project that take coordinates stored in a xml/kml file and displays them in a custom Google Maps application. I have everything working the way I want except for the reverse geocoding. I'm able to display the formatted address when I run the code inside the callback function but I can't find a way to store the address for later use (for dynamic events such as display the full address when a user clicks on the marker).

Is there any way to store the address inside the callback function and then get it later? Whenever I try, it says that address is undefined. See below:

var address;
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);

geocoder.geocode({'latLng': latlng}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
            address = results[1].formatted_address;
            alert(address); // this displays correctly
        }
        else {
            alert("No results found");
        }
    }
    else {
        alert("Geocoder failed due to: " + status);}
    }
);

alert(address); // this displays 'undefined'
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Austin
  • 23
  • 5

1 Answers1

1

Is there any way to store the address inside the callback function and then get it later?

Yes, but the problem is you're not trying to get it later. You're trying to get it immediately.

Let me explain. As is common in JavaScript, geocoder.geocode is asynchronous. That means that it does some work, and when the work is done it calls the callback, but here's the catch: it returns immediately. That means that when you do alert(address) on the last line, geocoder.geocode is still working, your callback hasn't been called yet, and address hasn't been set yet.

The solution is to work with address inside the callback, or (for organization's sake) define a function that you call from within the callback to do subsequent work.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • Thanks @Jordan, I figured it had to do with the callback being asynchronous. I simply just rewrote the `geocoder.gecode` code into my `click` handler event. – Austin Dec 18 '14 at 23:24