Search code examples
firebasegoogle-cloud-functionsgeofire

Firebase cloud functions find nearby locations


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.


Solution

  • 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/