I am querying a firestore collection for documents inside of a latitude and longitude range. Since it appears you can't conduct a query with arguments given to two different fields ('lat', 'lon'), I have assigned a type Geopoint to a single field 'coords' that has the longitude and latitude. How do I use .where() with geopoints? Below is the general query I would like to use, where _latMin, _latMax, etc. are variables linked to the bounding box of my map.
_getDocs() async {
print('getdocs');
final QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('collectionName')
.where(
'coords',
isGreaterThan: _latMin,
isLessThan: _latMax,
)
.where(
'coords',
isGreaterThan: _lonMin,
isLessThan: _lonMax,
)
.get();
snapshot.docs.forEach((DocumentSnapshot doc) {
print(doc.data());
});
}
How Do I reference the latitude and longitude inside of coords?
CodePudding user response:
A Firestore query can only contain range conditions (>
, >=
, etc) on one value. So you can filter on either the latitude or longitude of the coords
, but not on both in a single query.
If you want to perform geoqueries on Firestore at the moment, the common approach is to store an additional so-called geohash value in your document, which is a (rather magical) string value that combines latitude and longitude in a way that allows you to query them to filter on geographic blocks.
If you want to learn how this works, I recommend checking out this video on the topic: Querying Firebase and Firestore based on geographic location or distance.
If you want to implement this approach on top of Firestore, check out the documentation on implementing geoqueries on Firestore.
I also recommend checking out these previous questions on the topic: