我想自动显示用户地址的当前位置。
flutter中如何获取用户当前位置?
当我尝试运行示例程序时,它向我显示错误为
[错误:flutter/shell/platform/android/platform_view_android_jni.cc(40)] java.lang.NoClassDefFoundError:解析失败:Landroid/support/v4/util/ArraySet;
我正在使用 [地理定位器][1] 来获取纬度、经度
Future getLocation() async {
bool serviceEnabled;
LocationPermission permission;
// 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.
await Geolocator.openLocationSettings();
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
Position pos = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high)
.timeout(const Duration(seconds: 15), onTimeout: () {
return Future.error(
'Error fetching current location \nplease check Network and Location');
});
log("${pos.latitude}__${pos.longitude}");
return pos;
}
并通过[地理编码][2]获取地址
Future getAddress(lat, long) async {
List<Placemark> address = [];
try {
address =
await placemarkFromCoordinates(double.parse(lat), double.parse(long));
} catch (e, stackTrace) {
address = [];
Components.loggerStackTrace(e, stackTrace);
}
String loc = "";
for (var element in address) {
loc = '$loc${element.name}${element == address.last ? "" : ","}';
}
log(loc);
return loc;
}
从loc你可以得到地址 [1]:https://pub.dev/packages/geolocator [2]:https://pub.dev/packages/geocoding