我正在尝试使用 HTML5 geolocation 来获取当前访问者的位置。 出于隐私考虑,浏览器将提示用户允许/禁止与网站共享其位置。
如果用户不允许共享他们的位置,我想向控制台显示一条消息。
这是我所做的
$(function() {
// Try HTML5 geolocation.
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
findClosestStore(position.coords.latitude, position.coords.longitude);
}, displayMapWithAddressBar);
}
else
{
// Browser doesn't support Geolocation
console.log('browser does not support geolocation!')
displayMapWithAddressBar();
}
});
function displayMapWithAddressBar()
{
console.log('Show the map since the location was not detected!');
}
但是当用户拒绝共享他们的位置时,我在控制台中看不到任何内容。我希望看到一条消息:显示 map ,因为未检测到位置!
我如何知道用户拒绝共享其位置?
更新
我的代码在 Google Chrome 中按预期工作,但在 Firefox 中却不然。我怎样才能让它在所有浏览器中工作?
最佳答案
无法区分他们是否拒绝了权限,或者他们的浏览器是否根本不兼容(至少在 Firefox 中)。方法是使用地址栏显示 map ,或者任何默认行为,然后在他们接受时更新 UI。这段代码更简单......
displayMapWithAddressBar();
navigator.geolocation.getCurrentPosition(function(position){
findClosestStore(position.coords.latitude, position.coords.longitude);
});
关于javascript - 如何知道访问者拒绝与网站共享其位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40245696/