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
For this you can use
Distance matrix API
You can use the GeoFlutterFire library:
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.