I have set up a firebase realtime database with locations set up with both a latitude and a longitude in each node. In my android app, I have set it up so that it saves the user's initial location and then compares it to the latitude and longitude in the realtime database. I want to pull only the locations that are within a certain radius. I can't seem to find a way to create a function that would be able to do this. I can't use firestore because other aspects of my system rely on the realtime database.
This is the code to get the user's inital location on creation
Location initialValue = new Location("firstvalue");
double[] firstcoordinates = getGPS();
initialValue.setLatitude(firstcoordinates[0]);
initialValue.setLongitude(firstcoordinates[1]);
This is the getGPS function used to get the location
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
The inital location return works great. The issue is pulling only the values within a certain radius. Currently, the code below pulls all the locations.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public static FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
public static DatabaseReference mReferenceCrossings = mDatabase.getReference();
public static ArrayList<Location> results = new ArrayList<Location>();
String reference = "Crossings";
String orderKey = "Latitudes";
public ArrayList<Location> sortedQuery() throws InterruptedException {
return results;
}
interface FirebaseCallback {
void onCallback(ArrayList<Location> locations);
}
private ArrayList<Location> readData(FirebaseCallback firebaseCallback) {
ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot datasnapshot) {
for (DataSnapshot child : datasnapshot.getChildren()) {
double latitude = Double.parseDouble(child.child("Latitude").getValue().toString());
double longitude = Double.parseDouble(child.child("Longitude").getValue().toString());
Location entry = new Location("coordinates");
entry.setLatitude(latitude);
entry.setLongitude(longitude);
results.add(entry);
}
firebaseCallback.onCallback(results);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d("Firebase error", error.getDetails());
}
});
return results;
}
This is the firebase realtimedatabse with the values being used.
I only want to pull values within a certain radius, say 30 kms, instead of all of them. I would appreciate any help. Thank you so much.