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

  1. adapter.selectbyofferid
  2. return dist (undefined)
  3. call anonymous function used callback adapter.selectbyofferid
  4. call navigator.geolocation.getcurrentposition , return callback step 3
  5. 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

Popular posts from this blog

How do you change vbulletin's home page to the forums instead of the default (CMS or Activity Stream)? -

c++ - Troubles when compiling phash program -