2013-12-22 29 views
-1

我試圖獲取用戶當前位置(使用geolocation.getCurrentPosition())並將其存儲在JavaScript對象中,以便稍後使用它。將地理位置數據存儲在對象中

我似乎能夠存儲緯度和長度沒有問題,但我不能單獨檢索任何值。

這裏是我已經得到了代碼:

(function() { 
    'use strict'; 

    var location = { 
     data: {}, 
     get: function() { 
      var options = { 
       enableHighAccuracy: true, 
       timeout: 5000, 
       maximumAge: 0 
      }, 
      success = function(pos) { 
       var crd = pos.coords; 
       location.data.latitude = crd.latitude; 
       location.data.longitude = crd.longitude; 
      }, 
      error = function(err) { 
       console.warn('ERROR(' + err.code + '): ' + err.message); 
      } 
      navigator.geolocation.getCurrentPosition(success, error, options); 
     } 
    }; 
    location.get(); 
    console.log(location.data); // Shows data object with current lat and long values 
    console.log(location.data.latitude); // Undefined 
}()); 

還是一個的jsfiddle如果這是更簡單:http://jsfiddle.net/akpXM/

任何幫助是極大的讚賞。

回答

1

的地理位置API是異步的,你必須等待要返回的結果

(function() { 
    'use strict'; 

    var location = { 
     data: {}, 
     get: function (callback) { 
      var self = this, 
      options = { 
       enableHighAccuracy: true, 
       timeout: 5000, 
       maximumAge: 0 
      }, 
      success = function (pos) { 
       var crd = pos.coords; 
       self.data.latitude = crd.latitude; 
       self.data.longitude = crd.longitude; 
       callback(self.data); 
      }, 
      error = function (err) { 
       console.warn('ERROR(' + err.code + '): ' + err.message); 
      } 
      navigator.geolocation.getCurrentPosition(success, error, options); 
     } 
    }; 

    location.get(function(data) { 
     // the data is only available in the callback, after the async 
     // call has completed 

     console.log(data); // Shows data object with current lat and long 
     console.log(data.latitude); // now returns the latitude 
    }); 
}()); 

FIDDLE