Get nearest users within a circle by current location node js

纵饮孤独 提交于 2020-02-22 07:17:51

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/47218058/get-nearest-users-within-a-circle-by-current-location-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!