Turn on location services without navigating to settings page ? Flutter Dart
我们正在从 Flutter 迁移。我们使用此线程打开位置服务而不导航到设置页面
这在 Flutter 中如何实现?
导航到设置的当前临时代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | Future _getCurrentLocation() async { Position position; try { position = await Geolocator().getCurrentPosition( desiredAccuracy: LocationAccuracy.bestForNavigation); } on PlatformException catch(e){ print(e.code); if(e.code =='PERMISSION_DISABLED'){ print('Opening settings'); await openLocationSetting(); try { position = await Geolocator().getCurrentPosition( desiredAccuracy: LocationAccuracy.bestForNavigation); } on PlatformException catch(e){ print(e.code); } } } setState(() { // _center = LatLng(currentLocation['latitude'], currentLocation['longitude']); _center = LatLng(position.latitude, position.longitude); }); } Future openLocationSetting() async { final AndroidIntent intent = new AndroidIntent( action: 'android.settings.LOCATION_SOURCE_SETTINGS', ); await intent.launch(); } |
在屏幕主体中添加地图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | @override Widget build(BuildContext context) { return Scaffold( body: Builder( builder: (context) => Stack( children: [ GoogleMap( scrollGesturesEnabled: true, tiltGesturesEnabled: true, rotateGesturesEnabled: true, mapToolbarEnabled: true, mapType: MapType.normal, onTap: _placeMarker, onMapCreated: _onMapCreated, markers: Set.from(myMarker), initialCameraPosition: CameraPosition( target: _center, zoom: 5.0, ), ), Padding( padding: (EdgeInsets.symmetric(horizontal: 16, vertical: 40)), child: Align( alignment: Alignment.topRight, child: Column( children: [ CircleAvatar( radius: 30, child: IconButton( onPressed: () { navigate(context); }, icon: Icon( Icons.done, color: Colors.white, ), ), ), SizedBox( height: 10, ), CircleAvatar( radius: 30, child: IconButton( onPressed: **getLocation**, icon: Icon( Icons.location_on, color: Colors.white, ), ), ) ], ), ), ), Padding( padding: (EdgeInsets.symmetric(horizontal: 16, vertical: 40)), child: Align( alignment: Alignment.topLeft, child: Column( children: [ CircleAvatar( radius: 30, child: IconButton( onPressed: () { Navigator.pop(context); }, icon: Icon( Icons.chevron_left, color: Colors.white, ), ), ), SizedBox( height: 10, ), ], ), ), ) ], ), )); } getLocation() async { position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); print(position); mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition( target: LatLng(position.latitude, position.longitude), zoom: 18, tilt: 36))); } |
此代码将在主屏幕中初始化谷歌地图,如果位置被关闭,则会弹出一个警告框询问权限,然后它将自动打开
你可以使用定位包,你只需要在你的AndroidManifest.xml和Info.plist文件中添加所需的权限,权限会在弹出窗口中询问。