gpt4 book ai didi

javascript - navigator.geolocation 在位置服务关闭时在 iOS 上仍然为真

转载 作者:行者123 更新时间:2023-11-29 11:29:33 27 4
gpt4 key购买 nike

我读过的所有内容都说,为了检查地理定位是否可用,检查 navigator.geolocation。然而,在 iOS 上关闭了定位服务,它仍然可以通过检查。

它永远不会到达else

注意:我正在通过 https 进行测试。

if(navigator.geolocation)
{
// on iOS safari, with location services off (globally or at the app level) this will log
console.log('navigator.geolocation passes');
// navigator.geolocation.getCurrentPosition does exist
console.log(navigator.geolocation.getCurrentPosition);

// attempt to make the call
navigator.geolocation.getCurrentPosition((position)=>
{
// this will not get called
console.log('successfully retrieved position')
},
(error)=>
{
// this will not get called
console.log('error: ', error)
})
}
else
{
// I would expect this to be called but it doesn't get called
console.log('geolocation unavailable')
}

现在,当位置服务关闭时,我不会尝试获取位置,但问题是当它们关闭时,它不应该通过检查。

我想作为最后的手段,我可​​以只为坐标设置一个变量并检查它们是否未定义或者而不是依赖上面的 block ,但是如果有更好的方法来检查它那么我想要这样做。

编辑:我还应该提到,这只发生在清除浏览器设置后第一次加载页面时(至少在我的情况下)。在第一次加载时,它会通过检查然后挂起,因为不会调用其他任何东西。在第二次加载时,它似乎没有通过检查并调用了我们的后备选项。

编辑: 解决方案 是在检查之外设置一个变量。

// create a variable to hold the coordinates
let _coords = undefined;
// this is only a compatibility check
// not a check if it's available
if(navigator.geolocation)
{
// on iOS safari, with location services off (globally or at the app level)
// this block will be reached

// attempt to make the call to getCurrentPosition
navigator.geolocation.getCurrentPosition((position)=>
{
// this will not get called because location services are off
// doing something like doSomething(position.coords) will not get called
// instead, set the variable
_coords = position.coords;
},
(error)=>
{
// this will not get called since it's not an error
// doSomething(undefined);
})
}
else
{
// this block will not get reached since geolocation IS available,
// just not allowed. So again,
// doSomething(undefined) will not happen
console.log('geolocation unavailble')
}
// pass the variable (coords or undefined) to doSomething
doSomething(coords)

以上并没有解决整个问题,因为如果用户确实打开了位置服务,则 getCoordinates 是异步的,因此它将在接收坐标之前调用 doSomething 方法。

最佳答案

我认为此检查是通过测试地理位置对象的存在来实现兼容性:

// check for Geolocation support
if (navigator.geolocation) {
console.log('Geolocation is supported!');
}
else {
console.log('Geolocation is not supported for this Browser/OS.');
}

关于javascript - navigator.geolocation 在位置服务关闭时在 iOS 上仍然为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54929068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com