Reputation: 431
How do I return the latlon variable for codeAddress function. return latlon doesn't work, probably because of scope but I am unsure how to make it work.
function codeAddress(addr) {
if (geocoder) {
geocoder.geocode({ 'address': addr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
Upvotes: 0
Views: 2708
Reputation: 4050
You cannot return the result of geocoder.geocode
from codeAddress
since geocoder.geocode
will return its result to the callback/closure you provide. You have to proceed using a callback given as an argument to your function codeAddress
.
Returning anything from your callback given to geocoder.geocode
back to geocoder.geocode
will not make any sense in your application. You have to call some function in your application from the callback you provide to geocoder.geocode
.
This is explained in Geocoding Requests section of the API.
Upvotes: 0
Reputation: 12478
Declare a variable in the outer function, set it in the inner function and return it in the outer:
function codeAddress(addr) {
var returnCode = false;
if (geocoder) {
geocoder.geocode({ 'address': addr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b;
returnCode = true;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
return returnCode;
}
NOTE: This will only work if the inner function is run right away!
Upvotes: 1