问题
I have got a collection of documents with two fields: a location (Geopoint) and a distance (Number). The user input is another location (Geopoint).
I've to return all the documents where the distance between the location of the document and the location of the input is less than the distance of the document.
This tutorial shows how to perform nearby location queries but how can I insert in the equation the distance if it is not given by the user but different for each document?
回答1:
I came up with a solution.
Instead of saving a geopoint and a radius (representing a circle), I can store the circumscribed square, so I will store two longitudes (geopoint longitude + and - radius) and two latitudes (geopoint latitude + and - radius). Then I can do a compound query of 4 parts to see if the user geopoint is in the square.
Anyway, this is an imperfect solution because there is a lack of precision in the circle/square approximation, but in my specific case, it doesn't matter. Therefore if in your case precision matters you can save radius (or calculate from square wide), and then make a filter on the objects you queried.
Generalizing, this method can be easily applied to any polygon:
- Save in the firestore document the polygon coordinates and the circumscribed rectangle.
- Query the documents in Firestore using the four rectangle coordinates
- Filter results using the original polygons.
回答2:
You'll need to calculate the bounding box for your query, based on the position the user entered, and the maximum distance you want to return results for. When using geohashes (as the tutorial does), you'll actually need to calculate four bounding boxes: one in each quadrant from the center of the results that the user entered.
If you've never done this, it can be a bit hard to do it yourself, which is probably why the tutorial author doesn't cover it. But there are multiple Geo-libraries for Firestore which do this for you, and I'd highly recommend checking them out.
If you'd like to learn more about how the whole searching process works, I recommend checking out the video of my talk a while ago: Querying Firebase and Firestore based on geographic location or distance.
来源:https://stackoverflow.com/questions/61141656/firestore-double-field-query-request-and-with-geopoint