Search code examples
flutterfirebasedartgoogle-cloud-platformgoogle-cloud-firestore

Query Firestore documents on their GeoPoint latitude and longitude


Firestore recently added the functionality of having inequalities and range conditions on multiple fields in a single query.

I thought that it could be possible to query GeoPoints on their latitude and longitude separately. For example, I have the following GeoPoint: enter image description here

If I create the following query I cannot retrieve the document, even though the fromGeopoint.latitude is greater than 0.0 and the fromGeopoint.longitude is greater than -1.0.

StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance
          .collection('collection-name')
          .where('fromGeopoint.latitude', isGreaterThan: 0.0)
          .where('fromGeopoint.longitude', isGreaterThan: -1.0)
          .snapshots()

Is there something wrong with my approach? I know that I could do similar queries with geohashes or GeoFlutterFire but I was curious to know if that could be a potential geo query solution. Thank you.

I wasn't sure if I could access the latitude/longitude directly. People claim that it's possible. However, it does not work in my case. I tried different strings inside the 'where' clause like fromGeopoint.Latitude (with capital L as this is how it's stored in Firestore) or fromGeopoint.latitude() (which does not make any sense but I was playing around), etc


Solution

  • If I create the following query I cannot retrieve the document, even though the fromGeopoint.latitude is greater than 0.0 and the fromGeopoint.longitude is greater than -1.0.

    That's the expected behavior, because when you call where in this way:

    .where('fromGeopoint.latitude', isGreaterThan: 0.0)
    

    It means that the fromGeopoint field is a Map (object) that contains a key called latitude, and this is not correct because the fromGeopoint field is a field of type GeoPoint.

    I thought that it could be possible to query GeoPoints on their latitude and longitude separately.

    There is no way you can do that unless you save the latitude and longitude in two different separate fields.

    If you want to query a collection using a predefined GeoPoint then you have to pass a GeoPoint object to the where function and not a floating point number.