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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM