0

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

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

2 回答 2

1

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

于 2021-07-22T10:28:14.303 回答
0

通过此功能您将获得当前位置,无需经纬度

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;
       }
     }
于 2021-07-24T04:51:52.680 回答