Search code examples
fluttergoogle-cloud-firestoregeolocation

Flutter - How get documents from Cloud Firestore ordering by geo distance?


I have a dating app similar to Tinder but for specific niche, the app stores the latitude and longitude from the user in his document on Cloud Firestore database, I have a method that returns the distance from a user in meters, I am using GeoLocator for that and with this I know the distance between the current user and another user.

static String getDistanceBetween({
    double sourceLat, 
    double sourceLong,
    double currentLat,
    double currentLong
      }) {

    double _distanceInMeters = Geolocator.distanceBetween(
      sourceLat,
      sourceLong,
      currentLat,
      currentLong,
    );

    print(_distanceInMeters);

    if(_distanceInMeters == null){
      return "?";
    } else if(_distanceInMeters == 0.0){
      return "0";
    } else {
     return _distanceInMeters.toString().substring(0, 5);
    }


  }

When the user log in, I wanted to retrieve the nearest users first, what is the easiest way to retrieve documents from nearest users from the current user logged in?

If I could do something like this I think it solves the problem but I don't think it's possible to do with Firestore:

FirebaseFirestore.instance.collection("users").orderBy(getDistanceBetween(), descending: true).get().then((querySnapshot){

...
/// Get documents from users that are nearest to the current user

})

Firestore Data


Solution

  • There is no way to order by distance, as that requires the database to perform a calculation for each document, which would make it impossible to meet its performance guarantees.

    What you can do is retrieve the documents within a certain range from the second user. This is described in the Firestore documentation on geoqueries, but you can also read some of these previous questions on the topic, many of which use add-on libraries to accomplish the same.

    Once you've retrieved the documents within the range, you'll then need to order them by their distance in your application code.