I am trying to return a result from an asynchronous function in Javascript.
I have seen this question: How do I return the response from an asynchronous call?, and I am trying to implement the callback solution, but something is wrong.
This is my code:
function getLocation(callback){
var lat;
var long;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude;
long = position.coords.longitude;
}, function()
{
console.log('Please enable geolocation in your browser.');
});
} else {
alert('It seems like geolocation is not enabled in your browser.');
}
var res = {
"lat": lat,
"long": long
};
callback(res);
}
function getEventNearYou(){
var list = [];
getLocation(function(obj){
var lat = obj.lat;
var long = obj.long;
$.ajax({
url : 'http://www.skiddle.com/api/v1/events/search/?api_key=myapikey' + '&latitude=' + lat + '&longitude=' + long + '&radius=800&eventcode=LIVE&order=distance&description=1',
type : "GET",
async : false,
success : function(response) {
$(response).find("results").each(function() {
var el = $(this);
var obj = {
"eventname" : el.find("eventname").text(),
"imageurl" : el.find("imageurl").text(),
}
list.push(obj);
});
}
});
return list;
});
}
Basically, I want to find my current location, and create a HTTP get request to www.skiddle.com to retrieve events near that location.
This is how I call the function:
var x = getEventNearYou();
but I seem to have made a mistake, since I am getting the bad request error (lat
and long
are undefined).