views:

275

answers:

2

How do I return the latlon variable for codeAddress function. return latlon doesn't work, probably because of scope but I am unsure how to make it work.

function codeAddress(addr) { 
       if (geocoder) { 
           geocoder.geocode({ 'address': addr}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                    var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b;  
                    } else {
                       alert("Geocode was not successful for the following reason: " + status);
                   }

       });
     }  
   } 
A: 

Declare a variable in the outer function, set it in the inner function and return it in the outer:

function codeAddress(addr) { 
  var returnCode = false;
  if (geocoder) { 
    geocoder.geocode({ 'address': addr}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b;
        returnCode = true;
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }  
  return returnCode;
}

NOTE: This will only work if the inner function is run right away!

svinto
Which it might not do since geocoder.geocode might perform an asynchronous method invocation where the only way to return the result is through the callback provided.
Ernelli
A: 

You cannot return the result of geocoder.geocode from codeAddress since geocoder.geocode will return its result to the callback/closure you provide. You have to proceed using a callback given as an argument to your function codeAddress.

Returning anything from your callback given to geocoder.geocode back to geocoder.geocode will not make any sense in your application. You have to call some function in your application from the callback you provide to geocoder.geocode.

This is explained in Geocoding Requests section of the API.

Ernelli
Thanks I have ran up against this many times in jquery ajax callback and just wasn't thinking today. Thanks for the brain boost.
aran