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 update user current location.
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error("Location permission denied");
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error('Location permissions are permanently denied');
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
userLatLng = LatLng(position.latitude, position.longitude);
return position;
}
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 you\n${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.