I really need your help. I have some javascript code that is not behaving and I believe it has something to do with scope and timing based on the answers to this question here.
I'm fairly new to javascript programming so I'm not as well versed as I would like. I've been looking at my code but I can't seem to figure out where my problem lies.
function getCurrentAddress(marker) {
currentAddress = "Address: ";
geocoder.geocode({'latLng':marker.getPosition()}, function(results,status) {
console.log(results[1]);
if (status == google.maps.GeocoderStatus.OK) {
if (results[1])
currentAddress += results[1].formatted_address;
console.log(currentAddress);
} else {
currentAddress = "Geocoder failed due to: " + status;
}
});
console.log(currentAddress);
return currentAddress;
}
My problem lies in the fact that when I first query the contactAddress
variable it returns the formatted address from the result of the geocoding. But when the contactAddress
is queried right before the return the value is merely the default "Address: "
.
Also when I inspect the page the statement above the return happens before the results of the geocode. Is my function returning before it's ever calling the inner anonymous function? If so how do I fix that?
I tried moving the return statement into the geocode function but all that did was prevent my InfoWindows from opening for some reason.
I tried to make a jsfiddle to help you guys see what I was doing but it never worked quite right but here it is all the same http://jsfiddle.net/pxv2c/
Thanks guys for any help you can give.