Search code examples
javascriptfunctioncallbackreturn

Return variable in function from method callback data in same function


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);
                   }

       });
     }  
   } 

Solution

  • 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.