我正在尝试获取用户的当前位置(使用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/
任何帮助将不胜感激。
地理位置 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
});
}());
小提琴