1

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.

nekoMiaChan
  • 181
  • 2
  • 12
  • Which database are you using? Real Time Database or Firestore? – Renaud Tarnec Sep 19 '18 at 08:55
  • 1
    This might not be exactly what you are looking for, but it'll definitely help you get started. Take a look at [this](https://stackoverflow.com/a/43358909/4160532) – Kedarnag Mukanahallipatna Sep 19 '18 at 08:57
  • Real time db. could switch to the other if it is easier to perform geo queries. – nekoMiaChan Sep 19 '18 at 08:57
  • 1
    Some related posts on the web (not tested): https://www.youtube.com/watch?v=gYNwaKRWkVc, https://stackoverflow.com/questions/43567031/geofire-query-in-firebase-cloud-function – Renaud Tarnec Sep 19 '18 at 09:06
  • 1
    Since you tagged with `geofire`, did you try that library? While it is made for web, the code should (mostly at least) work fine in any JavaScript environment where a Firebase SDK exists. – Frank van Puffelen Sep 19 '18 at 14:16

1 Answers1

3

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

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/

MichaelSolati
  • 2,847
  • 1
  • 17
  • 29