为什么HTML5 Geolocation在不同的Web浏览器中具有不一致的错误行为

时间:2016-08-09 14:46:28

标签: javascript html5 google-chrome firefox

我一直在测试一个简单的code fragment,它使用HTML5地理定位功能返回经度和纬度值:



var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
&#13;
<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>
&#13;
&#13;
&#13;

我直接通过&#39;试用&#39;在Google Chrome中测试了代码。部分并返回&#39; error.PERMISSION_DENIED&#39;。但是当我在本地主机下的XAMPP中部署它时,它很有效。请注意,我已将Google Chrome设置为根据此documentation分享位置详细信息。

但是此代码返回&#39; error.POSITION_UNAVAILABLE&#39;在Firefox中甚至部署在XAMPP中,当我同意在Firefox中共享我的位置时。

是什么原因导致Google Chrome中的这种不一致行为(直接调用以及在localhost下部署时)以及通过Firefox访问时的行为?

1 个答案:

答案 0 :(得分:2)