如何返回低于10 km的距离的抖动

 收藏

设法按离用户位置最近的快照对我的快照进行排序,但是在仅显示返回距离10(km)内的快照时遇到了麻烦。我尝试编写if语句在distance函数中返回totalDistance,但是没有运气。任何帮助,将不胜感激!

  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);
      });
}
回复
  • 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.