将地理位置数据存储在对象中

时间:2013-12-22 21:20:14

标签: javascript geolocation

我正在尝试获取用户当前位置(使用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
}());

如果这更容易,可以使用JSFiddle:http://jsfiddle.net/akpXM/

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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