Search code examples
androidsearchgeolocationgoogle-maps-android-api-2

Find nearby users in Firebase Realtime DB


I would like to know how can I get all the users that are in a radius of the current user's location. So far I am able to get everyone's coordinates. What I am unable to do is get the users that are nearby fast without having to search the whole database (I am using Firebase Realtime DB). Is there an algorithm that can help with that?


Solution

  • The fastest and best way I found was using GeoFIre. In your onCreate() method add the following lines

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("path/to/geofire");
    GeoFire geoFire = new GeoFire(ref);
    

    Provided we have our location, then we can simply use GeoQueries in a method in order to get the result we want.

    // creates a new query around [latitude, longitude] with a radius of 10.00 kilometers
    GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(Double.parseDouble(latitude), Double.parseDouble(longitude)), 10.00);
    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
                @Override
                public void onKeyEntered(String key, GeoLocation location) {
                        Log.d("KEY", "KEY IS: " + key);
                        if (!key.equals(currentUserID) && !nearbyList.contains(key)) {
                            Log.d("KEY FOUND", "Key " + key + " entered the search area at" + location.latitude + "," + location.longitude);
    
                            usersRef.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                   /* Get your data from Firebase here */
                                }
    
                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {
    
                                }
                            });
                        }
                    }
                }
    
                @Override
                public void onKeyExited(String key) {
                    /* When someone exits the radius */
                }
    
                @Override
                public void onKeyMoved(String key, GeoLocation location) {
    
                }
    
                @Override
                public void onGeoQueryReady() {
    
                }
    
                @Override
                public void onGeoQueryError(DatabaseError error) {
    
                }
            });