【问题标题】:How to query all geoqueries in a set radius with geofirestore?如何使用geofirestore查询设置半径内的所有地理查询?
【发布时间】:2018-10-29 13:37:13
【问题描述】:

我正在尝试对云火库进行查询,该云火库应返回给定地理点半径为 10.5 公里的所有地理点。我正在尝试使用 geofirestore 来实现这一点。我曾尝试使用地理查询,但我找不到返回它的方法或属性。我的问题似乎有一个相当简单的答案,但我对 firebase 和 geofirestore 都是新手。谢谢。

到目前为止我的代码:

document.addEventListener('DOMContentLoaded', () => {
    const app = firebase.app();
});

var db = firebase.firestore();

db.settings({
    timestampsInSnapshots: true
});

const collectionRef = firebase.firestore().collection('geofirestore');

// Create a GeoFirestore index
const geoFirestore = new GeoFirestore(collectionRef);

const post1 =  db.collection('posts').doc('firstpost');

const test = {lat: 39.369048, long: -76.68229}

const geoQuery = geoFirestore.query({
    center: new firebase.firestore.GeoPoint(10.38, 2.41),
    radius: 10.5,
    query: (ref) => ref.where('d.count', '==', '1')
});

console.log(geoQuery.query());

【问题讨论】:

    标签: javascript firebase google-cloud-firestore geopoints geofirestore


    【解决方案1】:

    我认为文档可能不清楚,但这就是发生的事情。

    下面的代码创建了一个GeoFirestoreQuery

    const geoQuery = geoFirestore.query({
        center: new firebase.firestore.GeoPoint(10.38, 2.41),
        radius: 10.5,
        query: (ref) => ref.where('d.count', '==', '1')
    });
    

    如果您想进行地理查询,您可以使用on 侦听器来处理key_entered 事件,该事件将在您的查询中返回文档see here

    但是,您调用的是 query 函数,该函数返回 Firestore 查询或 CollectionReference(取决于您在创建或更新查询条件时是否传入了查询函数)。

    在这个query 上调用get 会绕过所有GeoFirestore 神奇的好处,并且不会为您提供您想要或期望的东西......相反,您会想做这样的事情。

    // Store all results from geoqueries here
    let results = [];
    
    // Create geoquery
    const geoQuery = geoFirestore.query({
        center: new firebase.firestore.GeoPoint(10.38, 2.41),
        radius: 10.5,
        query: (ref) => ref.where('d.count', '==', '1')
    });
    
    // Remove documents when they fall out of the query
    geoQuery.on('key_exited', ($key) => {
      const index = results.findIndex((place) => place.$key === $key);
      if (index >= 0) results.splice(index, 1);
    });
    
    // As documents come in, add the $key/id to them and push them into our results
    geoQuery.on('key_entered', ($key, result) => {
      result.$key = $key;
      results.push(result);
    });
    

    【讨论】:

    • 所以'key_exited'不是事件监听器?谢谢。
    • key_exited 是一个事件监听器,你应该可以在示例中找到它,它非常有用! =D
    • 我有同样的代码,有时它可以工作,有时它会失败:错误:函数在请求范围外崩溃函数调用被中断。不应该在某处等待吗?
    • 不需要等待,如果你展示一些代码或者分享一个要点我可以看看它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 2011-03-13
    • 2018-12-29
    • 2019-02-01
    相关资源
    最近更新 更多