3

I'm explaining with an example to achieve my result.

I have a users table. Each user has their location with latitude and longitude on the database. I'm using firebase database. So the DB looks like:

users {
  user-id{
     location{
        latitude
        longitude
     }
  }
}

I need to find users within a circle using my current location.

I've looked into geolib and found a method isPointInCircle . But using this, we need to iterate users data and needs to call this method on each loop. I need to avoid this multiple calls and achieve with only one method call like:

findNearestUsers(currentLocation,userLocations);

The result should be an array having nearest locations. How can I do this? Thanks in advance :)

Dinal Koyani
  • 455
  • 3
  • 6
Manu MT
  • 49
  • 1
  • 9

2 Answers2

2

GeoFire is the only way to query the Firebase Realtime Database based on proximity to a specific point, without having to download all data and filtering client side.

With GeoFire you create a GeoQuery for a location and a maximum distance:

var geoQuery = geoFire.query({
  center: [10.38, 2.41],
  radius: 10.5
});

You then attach handlers for items that fall within this range:

var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distance) {
  console.log(key + " entered query at " + location + " (" + distance + " km from center)");
});

There is no built-in functionality for finding a single, closest item. You could do that client-side based on the distance parameter in the callback. You'd still be retrieving more data than needed, but hopefully it'd be less than the entire database.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

There is no way to index and query the Firebase realtime database without getting the whole dataset and process locally.

I suggest switching to the new released beta Cloud Firestore instead which even has a geopoint as a data type and better support for sql-like "where queries".
Cloud Firestore queries

DaSe
  • 64
  • 5
  • Thanks for the suggestion. But I cannot try on my current project. Because almost done using firebase. I would try on my next project. Instead of the database can you suggest anything for the geolocation functionality? – Manu MT Nov 10 '17 at 08:58
  • While Firestore supports geo-data, it does [not currently support geo-queries](https://stackoverflow.com/a/46608540). There **is** a fine way to accomplish the same on the Firebase Realtime Database, it's a library called GeoFire. If you need geo-query support today today, that is the [recommended route](https://stackoverflow.com/a/46554998). – Frank van Puffelen Nov 10 '17 at 13:13