flutter 获取安卓手机定位 失败(仅安卓、仅定位)
生活随笔
收集整理的這篇文章主要介紹了
flutter 获取安卓手机定位 失败(仅安卓、仅定位)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1:使用 插件geolocator ,官網https://pub.dev/packages/geolocator
2:按照官網配置,代碼照抄
static Future<FlutterLocation> determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
Position p;
try {
//這里使用的權限申請插件 ,請自行搜索相關文檔配置獲取依賴
PermissionStatus permissionStatus = await LocationPermissions().requestPermissions();
if(PermissionStatus.granted == permissionStatus) {
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
// p = await AMapLocationClient.getLocation(true);
p = await Geolocator.getCurrentPosition();
print('location is get ${p}');
}
else{
await LocationPermissions().openAppSettings();
}
} catch (e) {
ToastUtil.showToast('獲取定位失敗:$e');
}
return FlutterLocation(p?.latitude, p?.longitude);
}
以上都是官網代碼,只新增了申請權限的代碼(其實加不加都一樣,實列代碼也可以申請權限)
然后自己封裝了一下經緯度
class FlutterLocation {
double lat;
double lng;
FlutterLocation(this.lat, this.lng);
}
正常情況下,大部分安卓手機調用這段代碼都能正確獲取手機定位,但是在部分機型上面,特別是華為手機上(我自己碰到的情況,不代表全部)不能正確獲取到手機定位,網上搜索資料,權限申請也添加了,gps定位也打開了,死活不行。
后來查資料發現,安卓手機獲取定位需要使用google服務來對gps返回信息進行解析,但是國內很多手機廠商都屏蔽了google服務,所有手機上即使獲取到了定位權限,也不一定能獲取到正確的定位,會一直阻塞在調用google服務上面,不報錯也不返回(卡死在determinePosition.then()這里,有時catcherror能返回)
那么這種情況有兩種解決方案
1:使用百度、高德api
2:對于定位精度要求不高的,可以使用web api的形式來獲取,比如:https://apis.map.qq.com/ws/location/v1/ip (需要自己申請key)
總結
以上是生活随笔為你收集整理的flutter 获取安卓手机定位 失败(仅安卓、仅定位)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cf13C Sequence(DP)
- 下一篇: 七天学会SALTSTACK自动化运维 (