getAddressWithDistance method
The function getAddressWithDistance
calculates the distance between a list of addresses and the
current location, returning a map of address components with their corresponding distances sorted in
ascending order.
Args: addresses (List
Returns:
The getAddressWithDistance
function returns a Future
that resolves to a Map
where the keys
are AddressComponent
objects and the values are double
values representing the distance between
each address in the input list and the current location. The distances are calculated in kilometers.
Implementation
Future<Map<AddressComponent, double>> getAddressWithDistance(
List<AddressComponent> addresses) async {
final myLoc = await _getCurrentPosition();
Map<AddressComponent, double> addressDistanceMap = {};
if (addresses.isNotEmpty) {
for (int i = 0; i < addresses.length; i++) {
final locA = LatLong(
lat: double.parse(addresses[i].latitude),
long: double.parse(addresses[i].longitude),
);
final locB = LatLong(
lat: myLoc.latitude,
long: myLoc.latitude,
);
final distance =
_distanceBetween(latLongA: locA, latLongB: locB); //Distance in KM's
Map<AddressComponent, double> addressWithDist = {
addresses[i]!: distance
};
addressDistanceMap.addAll(addressWithDist);
final sortedAddressDistance = addressDistanceMap.entries.toList()
..sort((a, b) => a.value.compareTo(b.value));
addressDistanceMap.clear();
addressDistanceMap.addEntries(sortedAddressDistance);
}
}
return addressDistanceMap;
}