Cordova geolocation watchPosition频率高于选项允许它

Kin*_*one 3 android geolocation angularjs cordova

在我的ionic/angularjs应用程序中,我使用的是geolocation插件: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);
Run Code Online (Sandbox Code Playgroud)

但是在Android上,频率远高于10秒(约0.5秒).在iOS上它很棒.这里有什么问题?

Dav*_*den 20

根据以下评论更新

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

本机位置管理器(Android和iOS)都是事件驱动的,即它们在GPS硬件以非固定间隔传送时会从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);
Run Code Online (Sandbox Code Playgroud)

然而,这不会使设备更频繁地停止请求更新,因此消耗相对大量的电池.

原生Android LocationManager允许您在请求位置时指定更新之间的最短时间以最小化电池消耗,但Android上的cordova-plugin-geolocation不实现直接使用LocationManager,而是使用W3C Geolocation API Specification in the本机webview,不允许您指定它.

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

它允许您指定:

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

fastInterval:显式设置最快的位置更新间隔,以毫秒为单位.