I have a function that is set up as follows
function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
}
var test = mainFunction();
alert(test);
To my logic, that alert should return ‘foo’, but instead it returns undefined. What am I doing wrong?
UPDATE: Here’s my actual code (it’s a function for reverse-geocoding with the Google API)
function reverseGeocode(latitude,longitude){
var address = "";
var country = "";
var countrycode = "";
var locality = "";
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
return geocoder.getLocations(latlng, function(addresses) {
address = addresses.Placemark[0].address;
country = addresses.Placemark[0].AddressDetails.Country.CountryName;
countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
return country;
});
}
you have to call a function before it can return anything.
Or:
for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the
getLocationsmethod and hence its return value is not recieved inside your main function.