skip to Main Content

I have a collection of Firebase locations with lat and long fields. Once a button is pressed in my flutter Android app, it will measure the distance between the user and the different locations and will be displayed in the UI. Below is the code for the Streambuilder.

StreamBuilder(
    stream: FirebaseFirestore.instance.collection("New Shop").snapshots(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        final List<LatLng> latLen = <LatLng>[];
        for (int i = 0; i < snapshot.data!.docs.length; i++) {
          latLen.add(LatLng(snapshot.data!.docs[i].get('lat'),
              snapshot.data!.docs[i].get('long')));
        }

        loadData() async {
          for (int i = 0; i < snapshot.data!.docs.length; i++) {
            markers.add(Marker(
              markerId: MarkerId(i.toString()),
              position: latLen[i],
              infoWindow: InfoWindow(
                title: snapshot.data!.docs[i].get('name'),
              ),
            ));
          }
        }

        loadData();

Below is the code to display the distance.

                              Expanded(
                            child: ListTile(
                              horizontalTitleGap: 10,
                              title: Text(
                                shop['name'],
                                maxLines: 1,
                              ),
                              subtitle: Text(
                                "${calculateDistance(userLatLng.latitude, userLatLng.longitude, shop['lat'].toDouble(), shop['long'].toDouble()).toStringAsFixed(2)}km from youn${shop['address']}",
                                maxLines: 2,
                              ),
                              isThreeLine: true,
                              contentPadding: const EdgeInsets.all(0),
                            ),
                          ),

I would like to sort the locations by the distance of the current user, however I cannot use orderBy as there is no distance field in the documents and the sorted list is unique to every user due to their different locations.

2

Answers


  1. For this you can use
    Distance matrix API

    Login or Signup to reply.
  2. You can use the GeoFlutterFire library:

    GeoFlutterFire is an open-source library that allows you to store and
    query a set of keys based on their geographic location…

    GeoFlutterFire stores data in its own format within your
    Firestore database. This allows your existing data format and Security
    Rules to remain unchanged while still providing you with an easy
    solution for geo queries."

    Note that with the current version you cannot use orderBy() (See "Limitations" section at the end of the doc), but you can sort the results in the frontend.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search