Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在对象中存储地理位置数据_Javascript_Geolocation - Fatal编程技术网

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
    });
}());