有没有一种方法来检查地理位置是否已被用JavaScript降低?

如果地理位置被拒绝,我需要JavaScript才能显示手动条目。

我曾经尝试过:

Modernizr.geolocation navigator.geolocation 

也不描述用户以前是否拒绝过地理定位。

watchPositiongetCurrentPosition都接受第二个callback,当有错误时调用它。 错误callback为错误对象提供了一个参数。 对于被拒绝的权限, error.code将是error.PERMISSION_DENIED (数值1 )。

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

例:

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

编辑:正如@I Devlin指出的那样,Firefox(4.0.1在这篇文章的时候)并不支持这种行为。 它在Chrome和Safari浏览器中可以正常工作

有了新的权限API,可以这样使用:

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

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

在你的情况下,如果用户明确拒绝访问,你想要做一些特定的事情。 您可以检查失败callback中的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 } } 

要解决Firefox的问题真的很容易。 在我的情况下,我把地理位置保存在一个叫做地理定位的Javascript的全局variables上。 在使用这个variables之前,我只是检查是否未定义,如果是这样,我只是从IP获取地理位置。

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

无论如何,这只是一个例子,你应该适应每一种情况。

 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:我没有足够的声望评论上面的答案,所以我不得不创build一个新的答案。 对于那个很抱歉。