return undefined value in jquery function -
i use code calculate distance between 2 gps positions. problem when return calculated value returns undefined value. please me
function calcdistane(offerid,userlocation){ var dist; var adapter = new locationadapter(); adapter.selectbyofferid(offerid,function(res){ navigator.geolocation.getcurrentposition(function(position){ var r = 6371; var userlocation= position.coords; dist= math.acos(math.sin(userlocation.latitude)*math.sin(res.item(0).lt) + math.cos(userlocation.latitude)*math.cos(res.item(0).lt) * math.cos(userlocation.longitude-res.item(0).lg)) * r; }); }); return dist; };
dist
isn't set yet when return. function setting dist callback. called after return outer (callback) function.
the order of execution is
- adapter.selectbyofferid
- return dist (undefined)
- call anonymous function used callback adapter.selectbyofferid
- call navigator.geolocation.getcurrentposition , return callback step 3
- when navigator.geolocation.getcurrentposition returns callback of call called , dist set. after step 2
you need pass continuation rather returning
function calcdistane(offerid,userlocation,callback){ var adapter = new locationadapter(); adapter.selectbyofferid(offerid,function(res){ navigator.geolocation.getcurrentposition(function(position){ var r = 6371; var userlocation= position.coords; callback(math.acos(math.sin(userlocation.latitude)*math.sin(res.item(0).lt) + math.cos(userlocation.latitude)*math.cos(res.item(0).lt) * math.cos(userlocation.longitude-res.item(0).lg)) * r); }); }); }
Comments
Post a Comment