我查看了Cordova Geolocation上的示例,但在弄清楚如何从其函数返回位置时遇到了麻烦,因此我可以在不同位置多次调用它。

这是获取职位的示例:

    var onSuccess = function (position) {
        alert('Latitude: ' + position.coords.latitude + '\n' +
            'Longitude: ' + position.coords.longitude + '\n' +
            'Altitude: ' + position.coords.altitude + '\n' +
            'Accuracy: ' + position.coords.accuracy + '\n' +
            'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
            'Heading: ' + position.coords.heading + '\n' +
            'Speed: ' + position.coords.speed + '\n' +
            'Timestamp: ' + position.timestamp + '\n');
    };

    function onError (error) {
        alert('code: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);


所以我希望能够调用一个函数并使其返回位置对象,它从“ onSuccess”中得到的结果

最佳答案

您可能正在寻找bind

var getPosition
function onSuccess(position){
  getPosition = function(position){
    // do somethin with the position object afterwards
  }.bind(null, position);
}

// ... some code or some timeout after onSuccess function has been fired

if(getPosition)getPosition();


只是为了弄清楚上面的代码应该如何工作:

// simulate cordova-geolocation-onSuccess call
onSuccess({x:2,y:5});

setTimeout(function(){

   if(getPosition)getPosition();

},2000);


希望这对您有所帮助,我已经正确理解了您的问题。

注意:bind可以用来创建一个函数,该函数可以在特定的上下文(第一个参数)中并通过某些传递的参数值(第二个,第三个...参数)执行。

根据您的以下评论:
您还可以使用回调函数作为参数来实现此目的:

function getUserPosition(callback) {
  function onSuccess(position) {
    callback(position);
  };
  $cordovaGeolocation.getCurrentPosition(options).then(onSuccess);
};

getUserPosition(function(position){
  // do something with position object here
});


但是,当您要使用可以真正返回地理定位对象的函数时,必须使用第一个答案。

10-07 12:46
查看更多