javascript - 地理位置在 x 次尝试后挂起,在浏览器重新启动后有效

标签 javascript html browser geolocation

我正在编写一个需要获取我的地理位置的脚本。它在大多数情况下都有效,但是时不时地无法获取地理位置,我必须重新启动浏览器才能使其再次工作。这种情况发生在 Safari 和 FF 中(未在 IE 和 Chrome 中测试)。有谁知道这可能是什么原因造成的?我正在使用《HTML 5》一书中的这段代码。

<script type="text/javascript">

function loadDemo() {
    if(navigator.geolocation) {
        document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser.";
        navigator.geolocation.getCurrentPosition(updateLocation);
    }
}

function updateLocation(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    if (!latitude || !longitude) {
        document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser, but location is currently not available.";
        return;
    }

    document.getElementById("latitude").innerHTML = latitude;
    document.getElementById("longitude").innerHTML = longitude;
}

最佳答案

FF有时会挂起,不知道safari怎么样。据我所知,它在 IE 中还不起作用。到目前为止,它在 Chrome 中似乎运行良好。 您可以通过设置超时来“解决”这个问题。它仍然不起作用,但至少脚本在一段时间后终止。我用这个代码。 如果您找到了好的解决方案,请告诉我。

    navigator.geolocation.getCurrentPosition(
        function(position) {
            //succes handler
        },
        function errorCallback(error) {
            //error handler
        },
        {
            enableHighAccuracy:false,
            maximumAge:Infinity,
            timeout:5000
        }
    );

关于javascript - 地理位置在 x 次尝试后挂起,在浏览器重新启动后有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4365988/

相关文章:

javascript - 鼠标悬停仅在第一次触发,为什么?

html - 更改窗口大小后我的网页变得困惑

javascript - 关闭浏览器选项卡时执行操作(Javascript)

css - 浏览器布局逻辑概述

javascript - 确定浏览器是否正在使用移动数据或 wifi?

javascript - Phaser 复杂碰撞

javascript - 继续报错说某物不是函数但找不到原因

javascript - 锁定父级滚动,只允许div滚动

php - 如何在php中插入sql查询时显示正确的消息?

html - 让子 ul 均匀地填充父 div 的 100% 宽度?