10

调用时如何将一个或多个参数传递给成功回调navigator.geolocation.getcurrentPosition

我怎样才能传递到deviceready方法?foundLocgetGeoLoc

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.');
    }
};
4

2 回答 2

22

将地理位置回调包装在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) {},
};

希望这可以帮助其他可能偶然发现这一点的人。

于 2013-08-06T14:22:49.150 回答
1

我发现这种方法更容易理解。

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
};
于 2018-08-25T12:31:41.263 回答