颤振取数位置与经纬度 [英] Flutter fetch Location and Latitude and Longitude
本文介绍了颤振取数位置与经纬度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我只能在一个变量中获取完整的位置(Placename、Latitude和经度),但我想在一个单独的变量中获取这三个信息。 以便我可以根据需要仅打印纬度、经度或地名。
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;
}
}
推荐答案
通过此函数,您将获得当前位置,而不会出现经度和经度
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;
}
}
这篇关于颤振取数位置与经纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文