如何知道访问者拒绝与网站分享他们的位置

How to know that a visitor refused to share their location with the site?

本文关键字:分享 他们的 位置 网站 何知道 访问者 拒绝      更新时间:2023-09-26

我正在尝试使用HTML5地理定位来获取当前访问者的位置。出于隐私考虑,浏览器将提示用户允许/不允许与网站共享他们的位置。

如果用户不允许共享他们的位置,我想在控制台显示一条消息。

这是我所做的

$(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!');
}

但是当用户拒绝分享他们的位置时,我在控制台上看不到任何东西。我希望看到一条消息说Show the map since the location was not detected!

我怎么知道用户拒绝分享他们的位置?

我的代码工作如预期在谷歌浏览器,但不是在Firefox。我怎么能让这个工作在所有的浏览器?

无法区分他们是否拒绝了权限,或者他们的浏览器只是不兼容(至少在Firefox中是这样)。这样做的方法是显示带有地址栏的地图,或者其他默认行为,然后在它们接受时更新UI。这段代码要简单得多…

displayMapWithAddressBar();
navigator.geolocation.getCurrentPosition(function(position){
    findClosestStore(position.coords.latitude, position.coords.longitude);
});