Firebase cloud functions find nearby locations

别来无恙 提交于 2021-01-28 09:40:59

问题


I need to find nearby vehicles within a specific radius to a given point and have those sorted by the distance from the given point. Does firebase provide a way to query geographical data? I need to do this within a cloud function. Entirely new to firebase so any help is appreciated.


回答1:


Using the geofire library you could do something like this...

exports.cloudFuncion = functions.https.onRequest((request, response) => {
  // logic to parse out coordinates
  const results = [];
  const geofireQuery = new GeoFire(admin.database().ref('geofireDatabase')).query({
      center: [coordinates.lat, coordinates.lng],
      radius: 15 // Whatever radius you want in meters
    })
    .on('key_entered', (key, coords, distance) => {
      // Geofire only provides an index to query.
      // We'll need to fetch the original object as well
      admin.database().ref('regularDatabase/' + key).on('value', (snapshot) => {
        let result = snapshot.val();
        // Attach the distance so we can sort it later
        result['distance'] = distance;
        results.push(result);
      });
    });

  // Depending on how many locations you have this could fire for a while.
  // We'll set a timeout of 3 seconds to force a quick response
  setTimeout(() => {
    geofireQuery.cancel(); // Cancel the query
    if (results.length === 0) {
      response('Nothing nearby found...');
    } else {
      results.sort((a, b) => a.distance - b.distance); // Sort the query by distance
      response(result);
    }
  }, 3000);
});

If you're not sure how to use geofire though I'd recommend looking at this post I made which will explain a lot of how geofire works and how to use it/



来源:https://stackoverflow.com/questions/52401909/firebase-cloud-functions-find-nearby-locations

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