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) {
}
});
geofire
key with Geofire, you can get the keys in a specific area with a geo-query. For examplevar geoQuery = geoFire.query({ center: [10.38, 2.41], radius: 10.5 });
For this example and much more, see the Geofire documentation: github.com/firebase/geofire-js/blob/master/docs/… – Leveyvar geoQuery = geoFire.query({ center: [10.38, 2.41], radius: 10.5 });
won't actually contain data about nearby locations on its own, but in combination with event listeners – ShinGeoFire is smart about how it looks for keys within the query. It does not need to load all of the GeoFire data into memory.
– Chatelain