简体   繁体   中英

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

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

This has to do with scope.

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

is returning to scope of codeAddress, but codeAddress doesn't return to caller's scope.

Since the call to geocode function is asynchronous, you have to use callbacks to use its results:

function codeAddress(zipCode,cb) {
    geocoder.geocode( { 'address': zipCode}, function(results, status) {
       //maybe you want to check status for error condition here
       var lat = results[0].geometry.location.d;
       var lng = results[0].geometry.location.e;
       var latlng = lat+'XX'+lng;

       cb(zipCode, latLng);
    });
}

var citymap = {};
function loadMap(cb) {
  $.ajax({                                      
        url: 'getdata.php',
        data: "query=geolocate",
        dataType: 'json',
        success: function (zips) {
            var i = 0,
                l = remaining = zips.length;

            for (; i <l; i++)    //better way to loop an array
            {
                var entry = zips[i];

                codeAddress(entry['zip_code'], function (zipCode,results){
                    citymap[zipCode] = {
                         scans: entry['num_scans'],
                         position: results;  
                    };

                    if (--remaining) {
                       cb();
                    } 
                });


            } 
        } 
  });
}

//call also loadMap with a callback to know when all zip are resolved
loadMap(function() {
    console.dir(citymap);    //all done!
});

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