Search code examples
javascriptfirebasefirebase-realtime-databasegeofire

Integrating Geofire with existing firebase database


I have gone through the github Fish examples for Geofire but still unclear of how to implement it within my app. My use case: My app shows events/meetups to logged in users. Currently within my app I have firebase listener at a firebase ref(events).

database.ref('events').orderByChild('startTime').on('value', (snapshot) => { 
 const feed = snapshot.val() || {}
})

Currently, at the initial load, the client app fetches the entire object at the events ref and then each of the events data is displayed to the user in a table(each row an event).

I understand that with geofire I can use the set() function to save each event key along with its geolocation[lat, lng]. And then using query I can retrieve the list of the event keys that fall within the specified radius to users current location(html5 geolocation). But What do I do with the keys, since there is no data attached to them, do I set individual "on" listeners for each event key at the Events ref? and then display the events data?


Solution

  • When you use Geofire, you end up with two branches in your JSON tree: one with the geodata for objects and one with the actual data.

    objects
      objectId1: { ... }
      objectId2: { ... }
      objectId3: { ... }      
    geodata
      objectId1: { ... }
      objectId2: { ... }
      objectId3: { ... }
    

    When you fire a GeoQuery against the geodata node, you get back the keys of the objects that fall within the range of that query. So for example objectId2 and objectId3.

    You then use that key to look up the corresponding JSON object under objects. For example when using key_entered:

    geoQuery.on("key_entered", function(key, location, distance) {
      console.log(key + " entered query at " + location + " (" + distance + " km from center)");
      ref.child("objects").child(key).once("value", function(snapshot) {
        console.log(snapshot.val());
      });
    });