Reputation: 577
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?
Upvotes: 1
Views: 4923
Reputation: 598728
Update (April 2024): Firestore recently added the ability to have inequality and range condition on multiple fields in a single query. See the documentation on Query with range and inequality filters on multiple fields and Optimize queries with range and inequality filters on multiple fields for full details.
I also wrote an article on Medium about this, comparing the cost of geohash based queries vs the newer approach with range conditions on multiple fields: How to perform geoqueries on Firestore (somewhat) efficiently
Old answer below 👇
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:
Upvotes: 20