如果您还没有安装 cordova-plugin-geolocation 到您的项目中 - 即 cordova plugin add cordova-plugin-geolocation - 这将为您的 Android 清单添加适当的权限,正如 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。如果您只想要一个位置,请在收到足够准确的位置后清除观察者。如果在添加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();