【发布时间】:2018-09-26 03:53:11
【问题描述】:
我正在尝试在 react-native 中获取 android 设备 (Android 7.0) 上的经纬度用户位置。当我打开 gps 时,它可以毫无问题地找到位置,但如果我想从 wifi 或地窖网络获取位置并且 gps 已关闭,它会给我错误“没有可用的位置提供程序”。
我在我的 android 清单中有这个权限,并在应用程序中动态检查它们:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
据我了解 enableHighAccuracy: true 为我提供来自 gps 的位置,而 enableHighAccuracy: false 应为我提供来自 wifi 或地窖网络的位置,但第二个无法正常工作。
这是我的代码:
let highAccuracySuccess = false;
let highAccuracyError = false;
let highAccuracy = true;
let timeout = 30000;
let getLowAccuracyPosition = () => {
console.log("REQUESTING POSITION", "HIGH ACCURACY FALSE");
navigator.geolocation.watchPosition(
position => {
console.log("POSITION NETWORK OK", position);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null
});
},
error => {
console.log(error);
this.setState({
error: "error2" + error.message
});
},
{
enableHighAccuracy: false,
timeout: 30000,
maxAge: 0
}
);
};
if (highAccuracy) {
console.log("REQUESTING POSITION", "HIGH ACCURACY TRUE");
const watchId = navigator.geolocation.watchPosition(
position => {
// location retrieved
highAccuracySuccess = true;
console.log("POSITION GPS OK", position);
navigator.geolocation.clearWatch(watchId);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null
});
},
error => {
console.log(error);
this.setState({
error: error.message
});
highAccuracyError = true;
navigator.geolocation.clearWatch(watchId);
getLowAccuracyPosition();
},
{
enableHighAccuracy: true,
timeout: 20000,
maxAge: 0,
distanceFilter: 1
}
);
setTimeout(() => {
if (!highAccuracySuccess && !highAccuracyError) {
getLowAccuracyPosition();
}
}, timeout);
}
【问题讨论】:
标签: android react-native android-gps