从navigator.geolocation.getCurrentPosition超时没有触发错误回调

Timeout from navigator.geolocation.getCurrentPosition is not triggering error callback

本文关键字:错误 回调 navigator geolocation getCurrentPosition 超时      更新时间:2023-09-26

我有以下Javascript代码,用于获取用户本地化:

navigator.geolocation.getCurrentPosition(getStores, getStoresError, {
    'enableHighAccuracy' : true,
    'timeout' : 10000,
    'maximumAge' : 0
});

当用户接受或拒绝本地化请求时,将调用两个回调。但是,如果在10秒内没有提供答案,我预计超时将过期并调用getStoresError。这是不可能的。什么好主意吗?

直到用户允许尝试计算他们的位置后,超时计时器才开始计数

 var options = {timeout:10000,enableHighAccuracy:true,maximumAge:0};
 navigator.geolocation.getCurrentPosition(getStores,getStoresError,options);

尝试创建一个全局变量,该变量只在navigator.geolocation.getCurrentPosition的成功方法上更新。然后你可以创建一个持续10秒的setTimeout函数来检查该值是否已经更新。

这样做的唯一问题是,如果用户单击Allow,而您的超时时间恰好在检索位置之前过期,您可能会过早地处理响应。

在开发环境中尝试了很多之后。我终于发现,从2016年开始,chrome在不安全的环境中禁用了该api,它必须从https完成,希望这会节省人们的时间。请看下面的链接https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only