Firebase云功能可找到附近的位置

时间:2018-09-19 08:54:22

标签: firebase google-cloud-functions geofire

我需要找到到给定点特定半径内的附近车辆,并按距给定点的距离对它们进行排序。 Firebase是否提供查询地理数据的方法?我需要在云功能中执行此操作。 完全不熟悉firebase,因此不胜感激。

1 个答案:

答案 0 :(得分:2)

使用geofire库,您可以执行以下操作...

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);
});

尽管您不确定I'd recommend looking at this post是如何使用geofire的,但我仍会解释geofire的工作原理和使用方法/