I for my life cannot figure this out. I know it’s some issue with the asynchronous way ajax makes calls but still cannot pin point the issue. I have this:
$(document).ready(function() {
$('#address').blur(function() {
console.log("now processing address");
var add = $("#address").val();
console.log("address is: " + add);
var refAdd = processAddress(add);
console.log("refined addres is: " + refAdd);
});
});
And then I have the processAddress function (thanks to another post on SO) which I’m calling. The issue is that the last statement above returns refAdd as undefined. Why is that??
function processAddress(address){
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(results[0].geometry.location);
console.log(results[0].formatted_address);
console.log("latitude is: " + results[0].geometry.location_type);
}
else {
console.log("Geocoding failed: " + status);
//formatted_address = "Geocoding failed: " + status;
formatted_address = "failed"
}
});
}
}
It’s pretty clear is a asynchronous issue, I can see in the order of how output is printed; refAdd should be printed last but it’s not.
now processing address
address is: 415 N Mathilda Ave, Sunnyvale
refined addres is: undefined
415 N. Mathilda Ave, Sunnyvale, CA, USA
latitude is: ROOFTOP
You are right, the problem is because the function is asynchronous (how do I know that? because as you said:
logsare written asynchronously andgeocoder.geocodeuses a callback). You have to use callbacks, like this:and in the function:
I do not know this
geocoderstuff, so you need to customize this to your own needs.