Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value for Javascript Function

I'm getting stuck on something that's probably pretty simple.

I can console.log a return value from the codeAddress function, but I can't get it to return to another function that calls it. The two lines in question are called out with comments.

Please don't mind my terrible XX concatenation; I'm just trying to figure out the function calls.

Any help would be greatly appreciated. Thanks!

function codeAddress(zipCode) {
    geocoder.geocode( { 'address': zipCode}, function(results, status) {
       var lat = results[0].geometry.location.d;
       var lng = results[0].geometry.location.e;
       var latlng = lat+'XX'+lng;
       return latlng;    // I can console log this value
     });
  }

var citymap = {};
function loadMap() {
  $.ajax({                                      
        url: 'getdata.php',
        data: "query=geolocate",
        dataType: 'json',
        success: function (zips) {
            for (var i in zips)
            {
                var entry = zips[i];
                citymap[entry['zip_code']]= {
                    scans: entry['num_scans'],
                    position: codeAddress(entry['zip_code'])  // But it will never return down here
                };
            } 
        } 
});
}
like image 511
renegadeborealis Avatar asked May 01 '26 08:05

renegadeborealis


1 Answers

For async functions, you need to provide a callback function, rather than expecting a return value. You should be invoking the "codeAddress" function like this:

var entry = zips[i];
var citymapForZip = {
    scans: entry['num_scans'],
};
var zipCode = entry['zip_code'];
citymap[zipCode] = citymapForZip;
codeAddress(zipCode, getCallbackFunction(citymapForZip));

I've used a helper function "getCallbackFunction", which should generate the callback function for the given city map. The callback will simply take the geocoding result, and set the citymap's "position" property. Like this:

function getCallbackFunction(citymap) {
    return function(result) {
        citymap.position: result; 
    };
}

And finally, your codeAddress function should, instead of returning "latlng", pass it to the callback:

function codeAddress(zipCode, callback) {
    geocoder.geocode( { 'address': zipCode}, function(results, status) {
       var lat = results[0].geometry.location.d;
       var lng = results[0].geometry.location.e;
       var latlng = lat+'XX'+lng;
       callback(latlng);
     });
  }
like image 185
McGarnagle Avatar answered May 03 '26 22:05

McGarnagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!