Firebase云功能可找到附近的位置 [英] Firebase cloud functions find nearby locations
本文介绍了Firebase云功能可找到附近的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到到给定点特定半径范围内的附近车辆,并按距给定点的距离对这些车辆进行排序.Firebase是否提供查询地理数据的方法?我需要在云功能中执行此操作.完全不熟悉firebase,因此不胜感激.
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.
推荐答案
使用 geofire
库,您可以执行以下操作...
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);
});
如果您不确定如何通过如何使用 geofire
,我建议您看一下这篇文章我所做的将解释 geofire
的工作原理以及使用方法/
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/
这篇关于Firebase云功能可找到附近的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文