0

我正在尝试编写一个返回表示设备位置的对象的函数:我尝试过:

  function getDevicePosition () {
    var positionObject;
    if (isDeviceReady) {
        navigator.geolocation.getCurrentPosition(function (position) {

            positionObject = position;
            console.log('location updated');
            console.log(positionObject.coords.longitude);//1. works
        }, function (err) {
            console.log('Failed to get device position' + err);
            return null;
        });

    } else {
        warnUser();
        return null;
    }
    console.log(positionObject.coords.longitude);//2. doesnt work as positionObject is null.
    return positionObject;
}

请注意,我添加了标记语句 1 和语句 2 的注释。如果我在语句 1 中初始化位置对象。为什么它在语句 2 中未定义?

4

2 回答 2

1

因为getCurrentPosition异步方法。标记为的2行将在回调函数有机会执行之前运行,所以positionObject仍然是undefined.

您需要将所有依赖于positionObject回调内部的代码移动到getCurrentPosition.

于 2012-09-28T10:01:55.347 回答
1

The call to navigator.geolocation.getCurrentPosition() is asynchronous, so the execution of the rest of the function does not wait until it is finished.

So your function is at execution basically reduced to this:

function getDevicePosition () {
    var positionObject;
    if (isDeviceReady) {
        // trigger some asynch function ...
    } else {
        warnUser();
        return null;
    }
    console.log(positionObject.coords.longitude);
    return positionObject;
}

From this code it should be pretty obvious, that at the point, your code reaches the console.log() your positionObject is not set, thus resulting in the error.

EDIT

With respect to your comment. The general design principle for such tasks is as follows:

// original function (triggered by a button or whatever)
function trigger() {
  // do some calculations before

  // trigger the position-retrival
  navigator.geolocation.getCurrentPosition(function (position) {
    // get the position
    // ...

    // call the handling function
    doStuff( position );
  });
}

// the function to do stuff based on the position
function doStuff( position ) {
// ...
}
于 2012-09-28T10:03:13.503 回答