2013-11-25 24 views
0

我剛剛在論壇上獲得了一些有關我的地理位置經理的幫助,因爲我遇到了一個難題。 我剛剛意識到地理位置是異步的。因爲我希望它同步以便於編程。 ^^jquery,在html5中使用推遲的地理位置

這裏的成品答案,這要歸功於making3: http://jsfiddle.net/x4Uf4/1/

GeoManager.prototype.init = function() { 
     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(this.updateLocation.bind(this)); 
     } else { 
      console.log("Geolocation is not activated!"); 
     } 
    }; 

    GeoManager.prototype.updateLocation = function (position) { 
     this.pos.lat = position.coords.latitude; 
     this.pos.lng = position.coords.longitude; 
    }; 


    var GM = new GeoManager(); 
    GM.init(); 

我使用$ .Deferred()莫名其妙地嘗試,但它只是失敗。有小費嗎? :)

+0

等什麼做你想做的事 –

+0

你想讓它被初始化 –

+0

我希望有一個回調我想,我可以用它設置之後的信息後讀取'pos'。由於它是異步的。我無法用同步處理它。邏輯 – andersfylling

回答

0

Arun P Johny在評論中回答了這個問題。

GeoManager = function() { 
    this.pos = { 
     lat: 0, 
     lng: 0 
    }; 
    console.log("Geo ok..."); 
}; 

GeoManager.prototype.init = function (callback) { 
    var self = this; 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function (position) { 
      self.updateLocation(position); 
      callback(position); 
     }); 
    } else { 
     console.log("Geolocation is not activated!"); 
    } 
}; 

GeoManager.prototype.updateLocation = function (position) { 
    this.pos.lat = position.coords.latitude; 
    this.pos.lng = position.coords.longitude; 

    console.log(this.pos); 
}; 

GeoManager.prototype.getLat = function() { 
    return this.pos.lat; 
} 
GeoManager.prototype.getLng = function() { 
    return this.pos.lng; 
}; 

//returns an object 
GeoManager.prototype.getPos = function() { 
    return this.pos; 
}; 

var GM = new GeoManager(); 
GM.init(function() { 
    console.log('pos', GM.getPos()) 
});