5

I have a javascript function which should return a geocoding for a string:

    function codeAddress(address) {
    var result = (new google.maps.Geocoder()).geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        return String(results[0].geometry.location.Ya)+','+String(results[0].geometry.location.Za)
      } else {
        return status;
      }
    });
    console.log(result);
    return result
}

However it returns "undefined". I understand the bug here,i.e, since javascript is asynchronous, its returning from the function codeAddress even before function(results, status) gets fully executed. But I need to know whats the solution here and the best practice.

1

1 Answer 1

11

Since it's asynchronous, you should pass a callback which handles the function:

function codeAddress(address, callback) {
    (new google.maps.Geocoder()).geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(String(results[0].geometry.location.Ya) + ','
                    + String(results[0].geometry.location.Za))
        } else {
            callback(status);
        }
    });
}

codeAddress("test", function(result) {
    // do stuff with result
});

If you're using jQuery, you could also use deferred:

function codeAddress(address, callback) {
    var dfd = new jQuery.Deferred();

    (new google.maps.Geocoder()).geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
             // trigger success
            dfd.resolve(String(results[0].geometry.location.Ya) + ','
                    + String(results[0].geometry.location.Za));
        } else {
            // trigger failure
            dfd.reject(status); 
        }
    });

    return dfd;
}

codeAddress("some address").then(
    // success
    function(result) {
        // do stuff with result
    },
    // failure
    function(statusCode) {
        // handle failure
    }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.