flutter中使用geolocator获取当前经纬度

geolocator插件地址

geolocator 插件是一个Flutter定位插件,支持 Android,iOS,macOS,Web,Windows中定位。

使用前需要针对不同平台配置权限,按照官网步骤完成即可。

示例:

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
import 'package:geolocator/geolocator.dart';

/// 确定设备当前位置。
///
/// 当位置服务未启用或权限 `Future`将返回一个错误。
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;

// 测试位置服务是否启用。
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// 位置服务未启用,请勿继续访问位置和请求用户的应用程序来启用位置服务。
return Future.error('位置服务已禁用。');
}

permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
//权限被拒绝,根据Android指南你的应用程序现在应该显示一个解释性的UI。
return Future.error('位置权限被拒绝');
}
}

if (permission == LocationPermission.deniedForever) {
// 权限永远被拒绝,请适当处理。
return Future.error(
'位置权限被永久拒绝,我们不能请求权限。');
}

// 当我们到达这里,得到许可,我们就可以继续访问设备的位置。
return await Geolocator.getCurrentPosition();
}