I'm having a difficult time understanding how GeoFire queries nearby locations;
I'm building a geo-based app that will fetch nearby locations based on the users location. My data is structured as follows
locations
-Ke1uhoT3gpHR_VsehIv
-Kdrel2Z_xWI280XNfGg
-name: "place 1"
-description: "desc 1"
geofire
-Ke1uhoT3gpHR_VsehIv
-Kdrel2Z_xWI280XNfGg
-g: "dr5regw90s"
-l
-0: 40.7127837
-1: -74.00594130000002
I can't seem to comprehend the whole idea of "tracking keys" and locations leaving & entering GeoQueries. (Perhaps this concept is more related to Uber-like functionality)
Assuming the locations
above are nearby, how exactly would I use my own lat and long coordinates to fetch them? I'm sure I'm misinterpreting GeoFires documentation but I'm just not seeing it.
To get all the locations which are nearby, first we get a Database reference to where we save our GeoFire locations. From your question, it should be
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("geofire");
Next we create a GeoFire instance with our GeoFire location reference as the argument
GeoFire geoFire = new GeoFire(ref);
Now we query the GeoFire reference,geoFire
using it's queryAtLocation
method
The queryAtLoction
method takes 2 arguments:a GeoLocation object and the distance range. So if we use 3 as the distance range, any location which is 3kilometers away from the user will show up in the onKeyEntered(...)
method.
NB: The GeoLocation object takes 2 arguments: latitude and longitude. So we can use the user's latitude and longitude as the arguments.
GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(userLatitde, userLongitude), 3);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
//Any location key which is within 3km from the user's location will show up here as the key parameter in this method
//You can fetch the actual data for this location by creating another firebase query here
Query locationDataQuery = new FirebaseDatabase.getInstance().child("locations").child(key);
locationDataQuery..addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//The dataSnapshot should hold the actual data about the location
dataSnapshot.getChild("name").getValue(String.class); //should return the name of the location and dataSnapshot.getChild("description").getValue(String.class); //should return the description of the locations
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onKeyExited(String key) {}
@Override
public void onKeyMoved(String key, GeoLocation location) {}
@Override
public void onGeoQueryReady() {
//This method will be called when all the locations which are within 3km from the user's location has been loaded Now you can do what you wish with this data
}
@Override
public void onGeoQueryError(DatabaseError error) {
}
});