Search code examples
firebasegoogle-cloud-firestorelocation

How can I get nearby points on map from Firestore without querying all the points in the database


I have a lot of locations (latitude and longitude) stored in the database. I am using Firestore. I have a point on the map ( latitude and longitude) and I want to get from the database only the locations that are maximum ~50m away from the specified point.

One way to do this is to get all the locations on the database and then iterate over them and select only the ones enough closer, but I fear that getting all the locations on the database and iterating over them will be too time costly.

Another way I had thought about is making a database query in which to include the distance function ( is quite complex), but firestore queries are using only simple functions ( equal, > etc.), also it s not possible to pass a lambda function to the query.

The third way to do this and the best that I can see is to divide the globe into small squares. A square would be something like the area from latitude X to (latitude X + 5') and longitude Y to (longitude Y + 5'). And to create these squares in the Firestore database I would do someting like this: A collection 'locationBuckets' which contains documents, each document representing a square and having the document id equal to '${X_latitude}-${Y_longitude}' . Each document representing a square will containt a collection with one document for every location in that square. So to get the nearby locations to a point first I would get the bucket in which the points is and after that I would get all the locations in the bucket and filter them. The query would look like this:

admin.firestore().collection("locationBuckets").doc(${X_latitude}-${Y_longitude}).collection('exactLocations').get().

My question is: Is the third way of querying good in terms of performance?

Thanks!

EDIT: The solution is firebase.google.com/docs/firestore/solutions/geoqueries on the first comment.


Solution

  • As part of the documentation for Firestore, there is an article called Geoqueries that can be found here:

    https://firebase.google.com/docs/firestore/solutions/geoqueries

    Please review that article and see if it resolves the story. In summary:

    Geohash is a system for encoding a (latitude, longitude) pair into a single Base32 string. In the Geohash system the world is divided into a rectangular grid. Each character of a Geohash string specifies one of 32 subdivisions of the prefix hash