Reputation: 329
Managed to sort my snapshots by those nearest to the user's location, but am having trouble showing only those that are within a returned distance of 10(km). I tried writing if statements above return totalDistance in the distance function, but no luck. Any help would be appreciated!
double calculateDistance(lat1, lon1, lat2, lon2){
var p = 0.017453292519943295;
var c = cos;
var a = 0.5 - c((lat2 - lat1) * p)/2 +
c(lat1 * p) * c(lat2 * p) *
(1 - c((lon2 - lon1) * p))/2;
return 12742 * asin(sqrt(a));
}
double distance(Position position, DocumentSnapshot snapshot){
final double myPositionLat = position.latitude;
final double myPositionLong = position.longitude;
final double lat = snapshot.data['latitude'];
final double long = snapshot.data['longitude'];
double totalDistance = calculateDistance(myPositionLat, myPositionLong, lat, long);
return totalDistance;
}
@override
void initState() {
super.initState();
subscription = collectionReference.snapshots().listen((data) async {
final location = await getLocation();
print('user location = $location');
final documents = data.documents;
documents.sort((a, b) {
final distanceA = distance(location, a);
final distanceB = distance(location, b);
return distanceA.compareTo(distanceB);
});
}
Upvotes: 0
Views: 179