1

I have a firestore collection with one of the fields of documents containing locations(geopoints) of users, I want build a listview with distance between current user and all other users in ascending order. How do I achieve in flutter?

It looks something like this https://i.stack.imgur.com/yXfME.png

Update

How can I get location from document in a list?

Illuminate
  • 109
  • 2
  • 10

1 Answers1

1

STEP 1 : Get the distance of current user with present list item in kilometers

var distanceInKms = GetDistance(latitude1, longitude1, latitude2, longitude2);


double GetDistance(double lat1, double lon1, double lat2, double 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));
  
}

STEP 2 : Add these values to the list item object. And Sort the list based on this field.

myList.sort((a,b) => a.distance.compareTo(b.distance));

Refer this question for further info on sorting.

Question: Hi, thanks how do i return this in listview and how do I get document from firestore in a list?

Answer :

QuerySnapshot snapshot = await Firestore.instance.collection("YOUR_COLLECTION_NAME").getDocuments();

List<items> myList = [];

snapshot.documents.forEach((doc) {
      //Convert incoming JSON info to object of your type and add to list
      myList.add(List.fromJSON(doc.data));
    });

//Apply logic on myList for sorting based on location
Abdul Malik
  • 1,158
  • 6
  • 15