I’m trying to do a simple geocode function for a map tool. I get the geocode fine, but I’m hoping to pass the location object back as the return value for the geocode function.
Something like this:
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
console.dir(location);
return location;
} else {
return false;
}
});
}
the console.dir of the location item shows the expected location object, so the function is being called and is successfully returning data.
this function is called by another process, which would then build the markers.
if (coordinates = codeAddress(myaddress){
// do stuff
}
However, the coordinates variable always evaluates as undefined, so the condition to “do stuff” is never met.
I know I’m probably missing something really obvious about the definition of the coordinates var, but I’m not sure what it is.
Thanks for help.
Basic code at: http://jsfiddle.net/2TXZ4/3/ though the map isn’t getting drawn for whatever reason.
The
geocodemethod is asynchonous so you need to do any processing in the callback you are providing to the method or you can provide a callback to yourcodeAddressmethod like this similar question/answer describes (How do I return a variable from Google Maps JavaScript geocoder callback?). In the code below, I moved what you were doing in thedoStufffunction into the callback of thegeocodefunction – it should work, but I can’t test it with the jfiddle link you provided (probably due to Google Maps API keys). I hope this helps!