具有超时的地理位置导致错误处理程序被调用两次

时间:2015-01-08 11:02:29

标签: javascript html5 geolocation

让我们举一个简单的例子:

navigator.geolocation.getCurrentPosition(
    function() { /* yay! */},
    function(error) { console.log(error) },
    {
        enableHighAccuracy: true,
        timeout: 5000
    }
);

在chrome中打开开发工具。点击模拟标签>传感器> "模拟位置不可用"。然后将此代码粘贴到控制台中。

您将立即收到以下日志:

PositionError {message: "PositionUnavailable", code: 2, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3}

然后5秒钟后你会收到:

PositionError {message: "Timeout expired", code: 3, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3}

这真的是API的设计方式,还是Chrome中navigator.geolocation实现中的错误?

两次调用的回调正在弄乱我的一些显示代码。有没有办法将错误捆绑在一起用于该请求,或者如果我们已经收到PositionUnavailable,则忽略超时?

1 个答案:

答案 0 :(得分:0)

好吧,我仍然认为这种行为很奇怪,但我找到了一种可靠地将错误捆绑在一起的方法。

以下是此示例的一些伪代码:

(function() {

    var detectionId = 0;

    var detectionErrors = {};

    var success = function() {};

    var error = function(id, error) {
        if (detectionErrors[id]) {
            return;
        }

        detectionErrors[id] = error;

        console.log(error);
    };

    document.getElementById('whatever').addEventListener('click', function() {
        navigator.geolocation.getCurrentPosition(
            success,
            error.bind(null, detectionId),
            {
                enableHighAccuracy: true,
                timeout: 5000
            }
        );

        detectionId++;
    });


})();