Flutter fetch Location 和经纬度

Flutter fetch Location and Latitude and Longitude

目前,我只能在一个变量中获取完整的位置(地名、纬度和经度),但我想在一个单独的变量中获取这三样东西。 这样我就可以根据需要只打印纬度或经度或地名。

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;
}
}

您使用了 geolocator: ^7.3.0 依赖项 here 您也可以使用此依赖项找到经纬度

通过此功能,您将获得没有经纬度的当前位置

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);
  

     return currentLocation;
    } catch (_) {
     print(_);
    return null;
       }
     }