如何将参数传递给getCurrentPosition成功回调函数?

10

当调用 navigator.geolocation.getcurrentPosition 时,我该如何传递一个或多个参数给成功回调函数?

我怎样才能把 foundLoc 中的 deviceready 参数传递给 getGeoLoc 方法?

var app = {

    onDeviceReady: function () {
        alert = window.alert || navigator.notification.alert;

        app.getGeoLoc('deviceready');
    },

    getGeoLoc: function (id) {
        navigator.geolocation.getCurrentPosition(this.foundLoc, this.noLoc, { timeout: 3 });
    },

    foundLoc: function (position) {
        var parentElement = document.getElementById('deviceready'); 
        var lat = parentElement.querySelector('#lat');
        var long = parentElement.querySelector('#long');

        lat.innerHTML = position.coords.latitude;
        long.innerHTML = position.coords.longitude;
    },

    noLoc: function () {
        alert('device has no GPS or access is denied.');
    }
};
2个回答

23

将地理位置回调函数用 function(position) {} 包裹起来。这样,你就可以向你的实际回调函数添加任意多的参数。

var app = {

    getGeoLoc : function (id) {

        var self = this;

        navigator.geolocation.getCurrentPosition(function(position) {

            var myVar1, myVar2, myVar3; // Define has many variables as you want here

            // From here you can pass the position, as well as any other arguments 
            // you might need. 
            self.foundLoc(position, self, myVar1, myVar2, myVar3)

        }, this.noloc, { timeout : 3});
    },

    foundLoc : function(position, self, myVar1, myVar2, myVar3) {},
};

希望这能帮助到其他可能会偶然发现这篇文章的人。


我偶然发现了它,确实帮了我不少。给你点赞 :) - John the Ripper
我对你的称呼感到困惑... 你能在例子中再加些内容吗? - Andrew Schultz

2

我发现这个方法更易于理解。

navigator.geolocation.getCurrentPosition(function (position) {
    updatePosition(position, var1, var2);
}, errorPosition, optionsPosition);

function updatePosition(position, var1, var2) {
    var coordinates = position.coords;
}

function errorPosition(error) {
    if (err.PERMISSION_DENIED === error.code) {

    }
}

var optionsPosition = {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 0
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接