2

I know this is a basic question, but I’m having a lot of trouble with it nonetheless.

I have a Firebase database storing community events. Each event node has a geo location node (created with GeoFire) called eventPlace (see screenshot below).

Using GeoFire (and javascript), how would I query the entire database and get all events within a certain location/radius? Is this possible, given the way the data is stored? Or do I need to move all the location nodes to a common node (eventPlaces??) and query that single parent node?

Note that I am not seeking real-time data. These locations are stored previously and don’t change very often.

Thanks in advance…

enter image description here

Ash8087
  • 643
  • 6
  • 16
  • 1
    Yes you need to have all the locations somewhere. I believe there are extensive documentation on this and others have answered similar questions so please do a bit of googling and you shall find. You need to store locations all under one node. and then keep track of their IDs to connect them with the rest of your data for each event. – TheBen Aug 26 '18 at 21:47
  • 1
    https://firebase.googleblog.com/2014/06/geofire-20.html – TheBen Aug 26 '18 at 21:47

1 Answers1

5

As it stands right now geofire sort of serves as an index to make geoqueries on, and provides the key of the document you want (which would be stored in a separate "collection").

You should be using geofire and a separate "collection" (call it eventPlaces)

var firebaseRef = firebase.database().ref('eventPlaces');
var geoFire = new GeoFire(firebaseRef);

Now you can use it as an index for your events, and can add items to it like so.

geoFire.set('-K_Pp-3RBJ58VkHGsL5P', [40.607765, -73.758949]);

Your Firebase RTDB will look like this now:

{
   'events': {
        '-K_Pp-3RBJ58VkHGsL5P': {
            // All your data here
        }
    },
   'eventPlaces': {
        '-K_Pp-3RBJ58VkHGsL5P': {
            'g': 'dr5x186m7u',
            'l': [40.607765, -73.758949]
        }
    }
}

So finally when you do a query on your geoFire:

geoFire.query({
  center: [40.607765, -73.758949],
  radius: 10
}).on('key_entered', (key, location, distance) => {
  console.log(key + ' entered query at ' + location + ' (' + distance + ' km from center)');
});

You'll end up being returned the key of the doc, for which you can do a normal Firebase query for that individual doc.

MichaelSolati
  • 2,847
  • 1
  • 17
  • 29