Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a geo "nearby" query with firestore?

Does the new firestore database from firebase natively support location based geo queries? i.e. Find posts within 10 miles, or find the 50 nearest posts?

I see that there are some existing projects for the real-time firebase database, projects such as geofire- could those be adapted to firestore as well?

like image 728
MonkeyBonkey Avatar asked Oct 08 '17 11:10

MonkeyBonkey


People also ask

Can I use realtime database and firestore at the same time?

You can use both Firebase Realtime Database and Cloud Firestore in your app, and leverage each database solution's benefits to fit your needs. For example, you might want to leverage Realtime Database's support for presence, as outlined in Build Presence in Cloud Firestore.


Video Answer


1 Answers

UPDATE: Firestore does not support actual GeoPoint queries at present so while the below query executes successfully, it only filters by latitude, not by longitude and thus will return many results that are not nearby. The best solution would be to use geohashes. To learn how to do something similar yourself, have a look at this video.

This can be done by creating a bounding box less than greater than query. As for the efficiency, I can't speak to it.

Note, the accuracy of the lat/long offset for ~1 mile should be reviewed, but here is a quick way to do this:

SWIFT 3.0 Version

func getDocumentNearBy(latitude: Double, longitude: Double, distance: Double) {      // ~1 mile of lat and lon in degrees     let lat = 0.0144927536231884     let lon = 0.0181818181818182      let lowerLat = latitude - (lat * distance)     let lowerLon = longitude - (lon * distance)      let greaterLat = latitude + (lat * distance)     let greaterLon = longitude + (lon * distance)      let lesserGeopoint = GeoPoint(latitude: lowerLat, longitude: lowerLon)     let greaterGeopoint = GeoPoint(latitude: greaterLat, longitude: greaterLon)      let docRef = Firestore.firestore().collection("locations")     let query = docRef.whereField("location", isGreaterThan: lesserGeopoint).whereField("location", isLessThan: greaterGeopoint)      query.getDocuments { snapshot, error in         if let error = error {             print("Error getting documents: \(error)")         } else {             for document in snapshot!.documents {                 print("\(document.documentID) => \(document.data())")             }         }     }  }  func run() {     // Get all locations within 10 miles of Google Headquarters     getDocumentNearBy(latitude: 37.422000, longitude: -122.084057, distance: 10) } 
like image 97
Ryan Lee Avatar answered Sep 22 '22 18:09

Ryan Lee