【问题标题】:Cordova geolocation watchPosition frequency is higher than the options allow itCordova 地理位置 watchPosition 频率高于选项允许的频率
【发布时间】:2016-05-19 13:29:53
【问题描述】:

在我的 ionic/angularjs 应用程序中,我使用的是地理定位插件:https://github.com/apache/cordova-plugin-geolocation

就像在文档中一样,我使用它来配置手表:

var watchOptions = {
    frequency : 10*1000,
    timeout : 60*60*1000,
    enableHighAccuracy: true // may cause errors if true
};

watch = navigator.geolocation.watchPosition(on_success,on_error,watchOptions);

但是在 android 上频率远高于 10 秒(约 0.5 秒)。在 iOS 上效果很好。这里有什么问题?

【问题讨论】:

    标签: android angularjs cordova geolocation


    【解决方案1】:

    根据以下 cmets 更新

    geolocation options 中没有frequency 参数可用于watchPosition(),因此您传递的任何值都将被忽略。通过watchPosition() 注册的成功回调在每次本地位置管理器从 GPS 硬件接收到位置更新(在enableHighAccuracy=true 的情况下)时被调用,因此它不会在固定的时间间隔内调用。

    本地位置管理器(Android 和 iOS)是事件驱动的,即当 GPS 硬件以非固定时间间隔提供更新时,它们会接收更新。因此,尝试对其应用固定频率就是尝试将方形钉安装在圆孔中 - 您不能要求 GPS 硬件每 N 秒准确地为您提供位置更新。

    虽然您可以按固定时间间隔调用getCurrentPosition(),但此方法只是返回最后收到的位置或请求新位置。

    如果问题是更新太频繁,可以记录每次更新的接收时间,N秒后才接受下一次更新,例如

    var lastUpdateTime,
    minFrequency = 10*1000,
    watchOptions = {
        timeout : 60*60*1000,
        maxAge: 0,
        enableHighAccuracy: true
    };
    
    function on_success(position){
        var now = new Date();
        if(lastUpdateTime && now.getTime() - lastUpdateTime.getTime() < minFrequency){
            console.log("Ignoring position update");
            return;
        }
        lastUpdateTime = now;
    
        // do something with position
    }
    navigator.geolocation.watchPosition(on_success,on_error,watchOptions);
    

    但是,这不会阻止设备更频繁地请求更新,因此会消耗相对大量的电池。

    原生 Android LocationManager 允许您在请求位置时指定更新之间的最短时间,以最大限度地减少电池消耗,但 Android 上的 cordova-plugin-geolocation 并未直接使用 LocationManager,而是使用 W3C Geolocation API Specification在本机 webview 中,不允许您指定。

    但是,您可以使用此插件来执行此操作:cordova-plugin-locationservices

    它将允许您指定:

    interval:设置活动位置更新所需的时间间隔,以毫秒为单位。

    fastInterval:明确设置位置更新的最快间隔,以毫秒为单位。

    【讨论】:

    • 在 iOS 上是否有 cordova-plugin-locationservices 的对应项?我能想到的一种解决方法是围绕默认的 watchPosition 创建自己的包装器,根据您给它的 frequency 值,您可以在其中调用 watchPositionclearWatch
    • 谢谢!但是,在您的示例代码中,我认为一行不正确,应该改为: if(lastUpdateTime && now.getTime() - lastUpdateTime.getTime()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多