有没有办法检查地理位置是否已被 Javascript 拒绝?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6092400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:11:45  来源:igfitidea点击:

Is there a way to check if geolocation has been DECLINED with Javascript?

javascripthtmlw3c-geolocation

提问by craigmoliver

I need JavaScript to display a manual entry if geolocation is declined.

如果地理位置被拒绝,我需要 JavaScript 来显示手动输入。

What I have tried:

我尝试过的:

Modernizr.geolocation
navigator.geolocation

Neither describes if user has previously declined access to geolocation.

两者都没有描述用户之前是否拒绝访问地理位置。

回答by Cristian Sanchez

watchPositionand getCurrentPositionboth accept a second callback which is invoked when there is an error. The error callback provides an argument for an error object. For permission denied, error.codewould be error.PERMISSION_DENIED(numeric value 1).

watchPosition并且getCurrentPosition都接受在出现错误时调用的第二个回调。错误回调为错误对象提供了一个参数。对于被拒绝的权限,error.code将是error.PERMISSION_DENIED(数值1)。

Read more here: https://developer.mozilla.org/en/Using_geolocation

在此处阅读更多信息:https: //developer.mozilla.org/en/Using_geolocation

Example:

例子:

navigator.geolocation.watchPosition(function(position) {
    console.log("i'm tracking you!");
  },
  function(error) {
    if (error.code == error.PERMISSION_DENIED)
      console.log("you denied me :-(");
  });

EDIT: As @Ian Devlin pointed out, it doesn't seem Firefox (4.0.1 at the time of this post) supports this behavior. It works as expected in Chrome and probablySafari etc.

编辑:正如@Ian Devlin 所指出的,Firefox(本文发布时为 4.0.1)似乎不支持这种行为。它将按预期在Chrome和可能Safari浏览器等。

回答by Endless

With the new permission api this is available as such:

使用新的权限 api,可以这样使用:

navigator.permissions.query({ name: 'geolocation' })
.then(console.log)

(only works for Blink & Firefox)

(仅适用于 Blink 和 Firefox)

http://caniuse.com/#feat=permissions-api

http://caniuse.com/#feat=permissions-api

回答by Josh Leitzel

According to the W3C geolocation specification, your getCurrentPositioncall can return a callback for success and a callback for failure. However, your failure callback will be invoked for anyerror that occurred, which is one of: (0) unknown; (1) permission denied; (2) position unavailable; or (3) timeout. [Source: Mozilla]

根据 W3C地理定位规范,您的getCurrentPosition调用可以返回成功回调和失败回调。但是,您的失败回调将针对发生的任何错误调用,这是以下之一:(0) 未知;(1) 许可被拒绝;(2) 职位不可用;或 (3) 超时。[来源:Mozilla]

In your case you want to do something specific if the user has explictly denied access. You can check the error.codevalue in your failure callback, like so:

在您的情况下,如果用户明确拒绝访问,您想要做一些特定的事情。您可以检查error.code失败回调中的值,如下所示:

navigator.geolocation.getCurrentPosition(successCallback,
    errorCallback,
    {
        maximumAge: Infinity,
        timeout:0
    }
);

function errorCallback(error) {
    if (error.code == error.PERMISSION_DENIED) {
        // pop up dialog asking for location
    }
}

回答by Kamae

To fix the Firefox problem is really easy. In my case I save the geolocation in a global variable on Javascript called geolocation. Before use this variable, I just check if is not undefined, if so I just get the geolocation from the IP.

修复 Firefox 问题真的很容易。在我的例子中,我将地理位置保存在 Javascript 上一个名为 geolocation 的全局变量中。在使用这个变量之前,我只检查是否未定义,如果是,我只是从 IP 获取地理位置。

In my website I don't have any problem getting the location the first time, but I saw in my short example that never has time to get the geolocation on the first time because is too quick.

在我的网站上,我第一次获取位置没有任何问题,但我在我的简短示例中看到,第一次获取地理位置的时间太快了。

Anyway this is just an example, you should adapt it in each case.

无论如何,这只是一个示例,您应该在每种情况下对其进行调整。

var geolocation = {};
getLocation();

$(document).ready(function(){
    printLocation(); // First time, hasn't time to get the location
});

function printLocation(){
    if(typeof geolocation.lat === "undefined" || typeof geolocation.long === "undefined"){
        console.log("We cannot get the geolocation (too fast? user/browser blocked it?)");
        // Get location by IP or simply do nothing
    }
    else{
        console.log("LATITUDE => "+geolocation.lat);
        console.log("LONGITUDE => "+geolocation.long);
    }
}

function getLocation() {
    // If the user allow us to get the location from the browser
    if(window.location.protocol == "https:" && navigator.geolocation)
        navigator.geolocation.getCurrentPosition(function(position){
            geolocation["lat"] = position.coords.latitude;
            geolocation["long"] = position.coords.longitude;
            printLocation(); // Second time, will be return the location correctly
        });
    else{
        // We cannot access to the geolocation
    }
}

PS: I don't have enough reputation to comment the above answers so I had to create a new answer. Sorry about that.

PS:我没有足够的声誉来评论上述答案,所以我不得不创建一个新答案。对于那个很抱歉。