简体   繁体   中英

How to check if locations are within map bounds on server with Google Firebase Cloud Functions

What I'm trying to do:

  • Function on Firebase Functions creates geocodes an address
  • There are a set of results that I want to verify are within the bounds of the map

Import FB Functions and Admin, Initialize

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

Handle CORS during testing

const cors = require('cors');
const corsHandler = cors({origin: true});

Google Maps Clients - google-maps-services-js

const googleMapsClient = require('@google/maps').createClient({
  key: 'xxxxxxx'
});

The main issue is that I want to query the db and have the backend check if the results are within the bounds of the map, filter the results down and respond. I don't want to get all the results and filter them on the frontend.

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
      });

    });

  });

});

It's easy to get the map's bounds and check if a location object is within bounds on the frontend:

map.getBounds().contains(marker.getPosition());

Struggling to get this working on the backend with Firebase Functions.

may be try

  return response.status(200).send({
    "data": results
  });

instead

  return response.status(200).send({
    "data": bounds
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM