我要做什么:
导入FB功能和管理,初始化
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
在测试过程中处理CORS
const cors = require('cors');
const corsHandler = cors({origin: true});
Google Maps客户端-google-maps-services-js
const googleMapsClient = require('@google/maps').createClient({
key: 'xxxxxxx'
});
主要问题是我想查询数据库并让后端检查结果是否在地图范围内,过滤结果并作出响应。我不想获得所有结果并在前端对其进行过滤。
exports.myFunction = functions.https.onRequest((request, response) => {
// CORS Container - allow all request origins
corsHandler(request, response, () => {
// Retrieve listings data from DB
return admin.database().ref('/listings').once('value').then(snapshots => {
// Geocode an address.
return googleMapsClient.geocode({
address: '1600 Amphitheatre Parkway, Mountain View, CA'
}, function(err, response) {
if (!err) {
let res = response.json.results;
let lat = res[0]["geometry"]["location"]["lat"];
let lng = res[0]["geometry"]["location"]["lng"];
// Want to get the bounds here
// let bounds = ???
let results = [];
// Filter snapshot results
snapshots.forEach(snapshot => {
// Get snapshot's position
const position = snapshot.val().position;
// Check if snapshot position is within map's bounds
if (bounds.contains(position)) {
results.push(snapshot);
}
});
return response.status(200).send({
"data": bounds
});
}
});
}).catch(e => {
return response.status(422).send({
"data": e
});
});
});
});
很容易获得地图的边界并检查位置对象是否在前端的边界内:
map.getBounds().contains(marker.getPosition());
正在努力通过Firebase Functions在后端上实现这一目标。
答案 0 :(得分:0)
可以尝试
return response.status(200).send({
"data": results
});
代替
return response.status(200).send({
"data": bounds
});