Flutter Firestore how to orderBy a stream based on distance

Viewed 28

I have a stream builder than returns a listview.builder

StreamBuilder(
              stream: FirebaseFirestore.instance
                  .collection('posts')
                  .orderBy(
                    'location',
                    descending: true,
                  )
                  .snapshots(),
              builder: (context,
                  AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(
                    child: CircularProgressIndicator(
                      color: primaryColor,
                    ),
                  );
                }
                //display posts
                return ListView.builder(

How can I sort the snapshots to closest first? I tried including the following method into the .orderBy() section but it doesnt seem to work.

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;
    var result = 12742 * asin(sqrt(a));
    return double.parse(result.toStringAsFixed(2));
  }
1 Answers

You will need to perform the sorting in your client-side application code.

What you can do is get an approximation of the list of results within a certain range from the database (as shown in the documented solution for geo-queries), but the results will not be ordered by distance, so you'll have to re-order them there too.

Related