目前,我只能在一个变量中获取完整的位置(地名、纬度和经度),但我想在单独的变量中获取这三个东西。这样我就可以根据需要仅打印纬度或经度或地名。
Future fetchLocation() async {
currentLocation = await getLocationCoordinates();
setState(() {
location = currentLocation;
});
}
Future<Map> getLocationCoordinates() async {
loc.Location location = loc.Location();
try {
await location.serviceEnabled().then((value) async {
if (!value) {
await location.requestService();
}
});
final coordinates = await location.getLocation();
return await coordinatesToAddress(
latitude: coordinates.latitude,
longitude: coordinates.longitude,
);
} catch (e) {
print(e);
return null;
}
}
Future coordinatesToAddress({latitude, longitude}) async {
try {
Map<String, dynamic> obj = {};
final coordinates = Coordinates(latitude, longitude);
List<Address> result =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
String currentAddress =
"${result.first.locality ?? ''} ${result.first.subLocality ?? ''}
${result.first.subAdminArea ?? ''} ${result.first.countryName ?? ''},
${result.first.postalCode ?? ''}";
print(currentAddress);
obj['Location'] = currentAddress;
obj['latitude'] = latitude;
obj['longitude'] = longitude;
return obj;
} catch (_) {
print(_);
return null;
}
}