简体   繁体   中英

Ordering QuerySnapShot with calculated field

I am getting a Firestore collection as QuerySnapShot.

 List userDocs = snapShot.data!.docs;

userDocs has a GeoPoint value and I am calculating the distance from the current user location to every userDocs GeoPoint item.

I am able to calculate the distance using a function, but I need to add this calculated distance as part of userDocs, in a way that I can sort the userDocs items from closest to farthest.

Here you have my attempt:

 List userDocs = snapShot.data!.docs;
          String distKm ="";
          //iterate para calcular la distancia al spot
          int i = 0;
          userDocs.forEach((e) {
            print("loop ${i}");
            print(e['spot_id']);
            //calculamos distancia
            GeoPoint geoPoint = e['location'];
            var latPost = geoPoint.latitude;
            var lonPost = geoPoint.longitude;
            var distancia = calculateDistance(
                widget.latitud, widget.longitud, latPost, lonPost);
            print("distancia  ${distancia}");
            distKm = distancia.toStringAsFixed(2);
            print("distkm ${distKm}");
            //update item in userDocs
            i++;
          });

Is there any way to add a new item to userDocs or update an existing (key,value) to be able to sort userDocs for nearest to farthest item?

EDIT

Function to calculate distances:

  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));
  }

Firestore doesn't have a built-in operator for distance based filtering, and it can only order/filter on values that are stored in the documents that it returns.

If you know the lat/lon pairs for both locations when you write the document, you can indeed also add a field with the distance you calculate based on that, and then use that field in queries.

If either of the locations is not known at write time, that is not an option. Your only option at that point would be to use geohash (or similar) based querying, as explained in the Firebase documentation ongeoqueries .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM