I'm trying to return a City from lat/long using a callback from AJAX, but the return is undefined although the AJAX is calling the callback with correct value (city).
I've been reading How do I return the response from an asynchronous call? but i am tryng to figure out why the City is still being returned and written as undefined.
Here's the whole code:
function getLocation(id) {
x = document.getElementById(id);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function showPosition(position) {
x.innerText = GetCity(position.coords.latitude, position.coords.longitude, returnCity);
});
} else {
this.innerHTML = "Geolocation is not supported by this browser.";
}
}
function returnCity(result) {
return result;
}
function GetCity(lat, long, callback) {
$.ajax({
type: "GET",
dataType: "json",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&sensor=false",
data: {},
success: function (data) {
var city;
$.each(data['results'], function (i, val) {
$.each(val['address_components'], function (i, val) {
if (val['types'] == "locality,political") {
if (val['long_name'] != "") {
city = val['long_name'];
} else {
city = "N/A";
}
}
});
});
callback(city);
},
error: function () {
alert('error');
}
});
}