【问题标题】:Firebase cloud functions find nearby locationsFirebase 云功能查找附近的位置
【发布时间】:2018-09-19 08:54:21
【问题描述】:

我需要找到特定半径范围内到给定点的附近车辆,并按与给定点的距离排序。 firebase 是否提供查询地理数据的方法?我需要在云功能中执行此操作。 对 Firebase 来说是全新的,因此感谢您提供任何帮助。

【问题讨论】:

  • 您使用的是哪个数据库?实时数据库还是 Firestore?
  • 这可能不是您想要的,但它肯定会帮助您入门。看看this
  • 实时数据库。如果执行地理查询更容易,可以切换到另一个。
  • 网络上的一些相关帖子(未测试):youtube.com/watch?v=gYNwaKRWkVc、stackoverflow.com/questions/43567031/…
  • 既然你用geofire标记,你试过那个库吗?虽然它是为网络设计的,但代码应该(至少)在任何存在 Firebase SDK 的 JavaScript 环境中都能正常工作。

标签: firebase google-cloud-functions geofire


【解决方案1】:

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

如果你不确定如何使用geofire 虽然I'd recommend looking at this post 我做了这将解释很多geofire 的工作原理以及如何使用它/

【讨论】:

  • 非常感谢。我设法将它用于我的场景。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2015-07-04
  • 1970-01-01
  • 2019-10-30
  • 2019-06-16
相关资源
最近更新 更多