Anuj Sharma Anuj Sharma - 1 month ago 17
Android Question

Filter Data using GeoFire

I am working on an App which is showing drivers on map. I used GeoFire for that. In my app, I need to show only those drivers who are available.
Please see the attached image for better info.

enter image description here

if

"is_hired":"0" && "driver_available":"true"
, only then should drivers display on the map, else they are removed from the map.

Right now, its displaying all drivers because I don't know how to filter drivers using its data on Firebase.

With GeoFire, I need to create a different node for updating the driver location and it has its overridden methods:

@Override
public void onKeyEntered(String key, GeoLocation location) {
Log.e("KEY","KEY-->> " + key);
Log.e("Location","Location-->> " + location.latitude+","+location.longitude);
Toast.makeText(HomeActivity.this, "Marker Added", Toast.LENGTH_SHORT).show();
// Add a new marker to the map
Marker marker = this.googleMap.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
this.driverMarkers.put(key, marker);
}

@Override
public void onKeyExited(String key) {
// Remove any old marker
Toast.makeText(HomeActivity.this, "Marker removed", Toast.LENGTH_SHORT).show();
Marker marker = this.driverMarkers.get(key);
if (marker != null) {
marker.remove();
this.driverMarkers.remove(key);
}
}

@Override
public void onKeyMoved(String key, GeoLocation location) {
// Move the marker
Marker marker = this.driverMarkers.get(key);
if (marker != null) {
this.animateMarkerTo(marker, location.latitude, location.longitude);
}
}


How can I filter those markers who are not hired and available?

Before GeoFire, I was using Firebase database queries. Its drawback was it was fetching entire database drivers. I need to show only nearby drivers.
Please help me in this.

Answer

The way to do this is to filter the drivers in the client inside onKeyEntered method.

@Override
public void onKeyEntered(String key, GeoLocation location) {
    ref.child("drivers").child(key).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Driver driver = dataSnapshot.getValue(Driver.class);
            if (driver.getIs_hired().equals("0") && driver.getDriver_available().equals("true")) {
                Marker marker = this.googleMap.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
                this.driverMarkers.put(key, marker);
            }
        }

        ...
    });
}

...

BTW, I use the equals method because the value for driver_available and is_hired in your database is in String, you might want to change them to Boolean and Integer

Comments