我一直在测试一个简单的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;
}
}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
我直接从“尝试一下”部分在 Google Chrome 中测试了代码,它返回了“error.PERMISSION_DENIED”。但当我将它部署在 localhost 下的 XAMPP 中时,它起作用了。请注意,我已将 Google Chrome 设置为基于此 documentation 共享位置详细信息.
但是,即使部署在 XAMPP 中并且当我同意在 Firefox 中共享我的位置时,此代码也会在 Firefox 中返回“error.POSITION_UNAVAILABLE”。
是什么导致 Google Chrome 中(直接调用时以及在本地主机下部署时)和通过 Firefox 访问时出现不一致的行为?
最佳答案
要共享位置,您需要安全连接。更多:https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
关于javascript - 为什么 HTML5 地理定位在不同的 Web 浏览器中出现不一致的错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853970/