cordova - 地理位置总是在 cordova 应用程序中超时

我正在开发一个使用 Cordova 3.5.0-0.2.7 打包的 Sencha Touch (2.3.1) 应用程序。我正在尝试使用以下方法读取 GPS 坐标:

navigator.geolocation.getCurrentPosition()

但是请求总是在 Android 手机上超时,而它在 Chrome 模拟器中工作正常。我也尝试过使用 watchPosition()。

如有任何帮助,我们将不胜感激。

最佳答案

如果您还没有,请安装 cordova-plugin-geolocation到您的项目中 - 即 cordova plugin add cordova-plugin-geolocation - 这将为您的 Android list 添加适当的权限,如 Mike Dailor正确地指出你需要。

您将哪些选项作为第三个参数传递给 getCurrentPosition()? geolocationOptions对象有 3 个属性:timeout、maxAge 和 enableHighAccuracy。

假设您想要一个准确的位置(即 GPS 跟踪/卫星导航类型的应用程序),设置 enableHighAccuracy: true 会使您的应用程序要求操作系统使用 GPS 硬件检索位置。在这种情况下,您需要设置一个超时值,让 GPS 硬件有足够的时间第一次获得定位,否则在它有机会获得定位之前就会发生超时。

另请记住,在 Android 设备上关闭 GPS(例如,将定位模式设置更改为“省电”)的效果因 Android 版本而异:操作系统永远无法检索高精度位置,因此会发生 TIMEOUT 错误(在 Android 上不会收到 PERMISSION_DENIED)或将检索并传递低精度位置,而不是使用 Wifi/cell 三角测量。

我建议使用 watchPosition() 而不是 getCurrentPosition() 来检索位置; getCurrentPosition() 在当前时间点对设备位置发出单一请求,因此位置超时可能发生在设备上的 GPS 硬件有机会获得定位之前,而使用 watchPosition() 您可以设置一个每次操作系统从 GPS 硬件接收到位置更新时,它将调用成功函数的观察者。如果您只想要一个位置,请在收到足够准确的位置后清除观察者。如果添加watcher时Android设备关闭GPS,会继续返回TIMEOUT错误;我的解决方法是在出现一系列后续错误后清除并重新添加观察者。

所以按照这些思路:

var MAX_POSITION_ERRORS_BEFORE_RESET = 3,
MIN_ACCURACY_IN_METRES = 20,
positionWatchId = null, 
watchpositionErrorCount = 0,
options = {
    maximumAge: 60000, 
    timeout: 15000, 
    enableHighAccuracy: true
};

function addWatch(){
    positionWatchId = navigator.geolocation.watchPosition(onWatchPositionSuccess, onWatchPositionError, options);
}

function clearWatch(){
    navigator.geolocation.clearWatch(positionWatchId);
}

function onWatchPositionSuccess(position) {
    watchpositionErrorCount = 0;

    // Reject if accuracy is not sufficient
    if(position.coords.accuracy > MIN_ACCURACY_IN_METRES){
      return;        
    }

    // If only single position is required, clear watcher
    clearWatch();

    // Do something with position
    var lat = position.coords.latitude,   
    lon = position.coords.longitude;
}


function onWatchPositionError(err) {
    watchpositionErrorCount++;
    if (err.code == 3 // TIMEOUT
        && watchpositionErrorCount >= MAX_POSITION_ERRORS_BEFORE_RESET) {        
        clearWatch();
        addWatch();
        watchpositionErrorCount = 0;
    }

}
addWatch();

https://stackoverflow.com/questions/31877268/

相关文章:

javascript - 检查字符串的第一个字符是否为数字会报错,表明 charat 不是有效方法

python - 如果在 Python 中出现异常重试

asp.net - ResponseMode ="File"不工作

Java - 编译器错误地解析 unicode 源文件

xml - Odoo:如何继承菜单项(使菜单项不可见)

php - Laravel 5.1 如何检查目录中是否存在文件?

sql - 如何用 SQL 删除 Oracle 数据库中的所有数据?

php - 学说 : Set CURRENT_TIMESTAMP as default value

batch-file - 批处理文件中的时间戳未正确更新

git - 为什么 git clone 有时创建一个 .git 目录,有时不创建?