How to query closest GeoPoints in a collection in Firebase Cloud Firestore?

17,346

Solution 1

We haven't exposed geoqueries yet, so currently there isn't a way to do this.

Historically, the Firebase Realtime Database used geohashes in a library called GeoFire--but given that we plan to expose actual geoqueries in the near future, we haven't updated that library to Firestore. To learn how to do something similar yourself though, have a look at this video.

Solution 2

A new project has been introduced since @problemsofsumit first ask this question. The project is called GEOFirestore.

With this library you can perform queries like query documents within a circle:

  const geoQuery = geoFirestore.query({
    center: new firebase.firestore.GeoPoint(10.38, 2.41),
    radius: 10.5
  });

You can install GeoFirestore via npm. You will have to install Firebase separately (because it is a peer dependency to GeoFirestore):

$ npm install geofirestore firebase --save

You can link to it via cdn: https://cdn.jsdelivr.net/npm/[email protected]/dist/geofirestore.min.js

Solution 3

You could let Algolia do the geo search with radius for you. All it would require is to build a cloud function that triggers on your wanted documents and sync them to Algolia.

Take a look at Geo Search https://www.algolia.com/doc/guides/searching/geo-search/

Also Firebase documentation advertises Algolia as a solution to complex searches here https://firebase.google.com/docs/firestore/solutions/search

Solution 4

Rather than use third party services like Algolia I would use the new library that came out for both iOS and Android that replicates GeoFire for Firestore. The new library, called GeoFirestore, is fully documented and well tested. I have used this library already in many demo projects and it seems to work perfectly. Give it a shot!

Share:
17,346
ProblemsOfSumit
Author by

ProblemsOfSumit

I work at Stripe. I also build profitable SaaS projects in public and sharing the journey on Twitter and YouTube.

Updated on June 07, 2022

Comments

  • ProblemsOfSumit
    ProblemsOfSumit about 2 years

    The new Firestore DB allows me to store GeoPoints. Is there a way to query based on them?

    So for example if each of my collections documents got a location field of the type geopoint. How can I get the closest 10 documents to an arbitrary coordinate?

    The documentation doesn't seem to cover this. I tried stuff like this:

    someRef.where('location', '>', geopoint).limit(10).get();
    

    Obviously this doesn't make much sense but I'm just trying out some stuff here 😅