如何使用geofirestore查询指定半径内的所有地理位置?

时间:2018-10-29 13:37:13

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

我正在尝试查询一个云存储,该存储应返回距给定地理点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());

1 个答案:

答案 0 :(得分:0)

我认为文档可能不清楚,但这是怎么回事。

下面的代码创建一个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(取决于您在创建或更新查询条件时是否传入查询函数)。

在此get上调用query绕过了GeoFirestore的所有魔法优势,并且不会为您提供您想要或期望的东西。相反,您想要做这样的事情。 / p>

// 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);
});
相关问题