Search code examples
javascriptnode.jsgoogle-mapsfirebase-realtime-databasegeolocation

Get nearest users within a circle by current location node js


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 :)


Solution

  • 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.