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.
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
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With