function getLatLng(address) {
geocoder.geocode({
'address' : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Aus getLatLng: adresse:"+address+"Ergebnis: "+results[0].geometry.location);
return results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: "
+ status);
}
});
}
I am using this javascript function in another function to get the Latitude/Longitude values from a string which is the address. The alert shows that the conversion is successfull but if i call the method i get a javascript error that it’s still undefined.
var start = document.getElementById("route_start").value;
start = getLatLng(start);
alert("Start: "+start);
What am i missing? The alert always shows an undefined variable. Why is that?
I tried everything. Everything is going well til i call the function getLatLng. Something with the return isn’t working. 🙁
Your
getLatLngfunction doesn’t actually return anything, which is whystartis undefined.The return statement that you have written is contained within the anonymous function that gets passed to
geocoder.geocode, so this won’t actually get returned from your outer function.Since
geocoder.geocodeis asynchronous you won’t be able to write agetLatLngwhich returns the result in this way, instead you need to pass a callback function as an argument and invoke this function when the geocode API returns a value, something like: