如何使用Google Firebase Cloud Functions检查位置是否在服务器上的地图范围内

问题描述 投票:0回答:1

我想做什么:

  • Firebase函数上的函数创建地址的地理编码
  • 我要验证的一组结果在地图的边界

导入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 Clients-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在后端上实现此目的。

node.js firebase google-maps google-cloud-functions google-maps-markers
1个回答
0
投票
可以尝试
© www.soinside.com 2019 - 2024. All rights reserved.