James Piner
James Piner

Reputation: 329

How to return distances below 10km way flutter

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

Answers (1)

rgov
rgov

Reputation: 4359

Try using where to filter the list. I've never used Dart but I imagine it looks something like this:

final documents = data.documents.where((a) => distance(location, a) < 10);

Maybe tack on .toList(); if you want an actual List and not an Iterable.

Upvotes: 1

Related Questions