Javascript 在对象中存储地理位置数据
我正在尝试获取用户的当前位置(使用Javascript 在对象中存储地理位置数据,javascript,geolocation,Javascript,Geolocation,我正在尝试获取用户的当前位置(使用geolocation.getCurrentPosition()),并将其存储在JavaScript对象中,以便以后使用 我似乎能够毫无问题地存储lat和long,但我无法单独检索这两个值 以下是我得到的代码: (function() { 'use strict'; var location = { data: {}, get: function() { var options = {
geolocation.getCurrentPosition()
),并将其存储在JavaScript对象中,以便以后使用
我似乎能够毫无问题地存储lat和long,但我无法单独检索这两个值
以下是我得到的代码:
(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
}());
如果更容易的话,也可以使用JSFIDLE:
非常感谢您的帮助。地理定位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
});
}());