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

Geolocation with timeout causes error handler to be called twice

本文关键字:调用 程序 两次 处理 错误 超时 地理位置      更新时间:2023-09-26

让我们举这个失败的简单例子:

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,则忽略超时?

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

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

(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++;
    });

})();