有没有办法用Javascript检查地理位置是否被拒绝?
如果地理位置被拒绝,我需要JavaScript显示一个手动输入 我所尝试的:有没有办法用Javascript检查地理位置是否被拒绝?,javascript,html,w3c-geolocation,Javascript,Html,W3c Geolocation,如果地理位置被拒绝,我需要JavaScript显示一个手动输入 我所尝试的: Modernizr.geolocation navigator.geolocation 两者都不描述用户以前是否拒绝访问地理位置。watchPosition和getCurrentPosition都接受第二次回调,当出现错误时会调用该回调。错误回调为错误对象提供参数。对于被拒绝的权限,error.code将是error.permission\u denied(数值1) 请在此处阅读更多信息: 例如: navigato
Modernizr.geolocation
navigator.geolocation
两者都不描述用户以前是否拒绝访问地理位置。
watchPosition
和getCurrentPosition
都接受第二次回调,当出现错误时会调用该回调。错误回调为错误对象提供参数。对于被拒绝的权限,error.code
将是error.permission\u denied
(数值1
)
请在此处阅读更多信息:
例如:
navigator.geolocation.watchPosition(函数(位置)){
log(“我在跟踪你!”);
},
函数(错误){
if(error.code==error.PERMISSION\u DENIED)
log(“你拒绝了我:-(”);
});
根据W3C,您的getCurrentPosition
调用可以返回成功回调和失败回调。但是,对于发生的任何错误,都将调用失败回调,这些错误包括:(0)未知;(1)权限被拒绝;(2)位置不可用;或(3)超时。[]
在您的情况下,如果用户明确拒绝访问,您需要执行一些特定的操作。您可以在失败回调中检查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上名为geolocation的全局变量中。在使用此变量之前,我只需检查是否未定义,如果是,我只需从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:我没有足够的声誉来评论上述答案,因此我必须创建一个新的答案。对此表示抱歉。在不提示用户的情况下,您可以使用新的权限api。该api如下所示:
navigator.permissions.query({name:'geolocation'})
.然后(console.log)
内联权限检查
可能的值有提示
、授予
和拒绝
const permissionStatus = await navigator?.permissions?.query({name: 'geolocation'})
const hasPermission = permissionStatus?.state // Dynamic value
注意:这需要处于async
函数中
默认值:
如果要处理失败的案例,请在第二行中添加可选的??myDefaultValue
链接:
内联空检查-?。
回退值-??
-等待
?
中都有一个副本,用于显示内联空检查的使用情况。
提示:@babel/插件建议可选链接已接受的答案更改为@unfinal