Firebase 云功能查找附近的位置
Firebase cloud functions find nearby locations
我需要在给定点的特定半径范围内找到附近的车辆,并按距给定点的距离对这些车辆进行排序。
firebase 是否提供查询地理数据的方法?我需要在云功能中执行此操作。
对 firebase 完全陌生,非常感谢您的帮助。
使用 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
,虽然 我做了这将解释很多 geofire
的工作原理和使用方法/
我需要在给定点的特定半径范围内找到附近的车辆,并按距给定点的距离对这些车辆进行排序。 firebase 是否提供查询地理数据的方法?我需要在云功能中执行此操作。 对 firebase 完全陌生,非常感谢您的帮助。
使用 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
,虽然 geofire
的工作原理和使用方法/