0

I am trying to get a location name according to a lat-long coordinate from the Google maps geocoder. I cannot seem to extract the value from the geocoder callback. Here is my code:

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

geocoder.geocode({'latLng': latlng } , function(results,status) {

    if (status == google.maps.GeocoderStatus.OK) {
        address = results[1].formatted_address; //want to get this address
    } else {
        address = 'error';
    }
});

window.alert(address) 
//address is an empty string here, but I want the value from inside the geocoder
//want access to address here to do other operations with it

The documentation for geocoder on the Google Developers site is almost non existant, and I am having problems trying to find an example that is similar. I am out of my comfort area here, so any help would be great!

Elias
  • 1,367
  • 11
  • 25
  • The geocoder is asynchronous, you need to _use_ the value inside the callback routine when/where its value is available. – geocodezip May 28 '14 at 21:37

1 Answers1

1

The call is asynchronous, so the value exists inside the callback function:

geocoder.geocode({'latLng': latlng } , function(results,status) {
  if (status == google.maps.GeocoderStatus.OK) {
    address = results[1].formatted_address; //want to get this address
  } else {
    address = 'error';
  }
  window.alert(address);
});

// The code here runs before the callback function
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Sorry for the misunderstanding, but I want to have access to the address outside of the callback so I can do operations on it. – Elias May 28 '14 at 21:40
  • @Elias: You can't do that. The value doesn't exist yet when you are outside the callback. The callback can't run until you have exited the function that contains the `geocode` call. – Guffa May 29 '14 at 12:21