简体   繁体   中英

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

       });
     }  
   } 

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM