Search code examples
javaandroidfirebasegoogle-maps-markersgeofire

How to count markers within the user radius using geofire query in android?


Here is my code I add marker to the location within the radius

GeoQuery geoQuery = geoFire.queryAtLocation( new GeoLocation( latitude, longitude ), 1 );

HashMap<String, Marker> markers = new HashMap<>();

geoQuery.addGeoQueryEventListener( new GeoQueryEventListener() {
    @Override
    public void onKeyEntered(String key, GeoLocation location) {
        countCrime++;

        if (isAttachedToActivity()) {

            //get string icon using filename
            int resourceID = getResources().getIdentifier(
                    data.getIcon(), "drawable",
                    getActivity().getPackageName() );

            //bitmapDescriptor for marker using filename
            BitmapDescriptor crime_icon = BitmapDescriptorFactory.fromResource( resourceID );

            LatLng latLng = new LatLng( latitude, longitude );

            Marker marker = mGoogleMap.addMarker( new MarkerOptions().position( latLng )
                    .icon( crime_icon ) );
            markers.put( key, marker );
            
            marker.setTag( details );
        }
    }
}

Here is the Output: Here is the Output

I want to count the marker in the radius


Solution

  • The easiest way to count the keys inside the geoquery, is to keep a counter variable and increase that every time is called. Then when is called to indicate that all keys have been loaded, you know how many there are.

    In code:

    geoQuery.addGeoQueryEventListener( new GeoQueryEventListener() {
        int keyCount = 0; // 👈
    
        @Override
        public void onKeyEntered(String key, GeoLocation location) {
            keyCount++; // 👈
    
            ...
        }
    
        @Override
        public void onKeyExited(String key) {
            keyCount--; // 👈
        }
    
        @Override
        public void onGeoQueryReady() {
            System.out.println("There are now "+keyCount+" keys in range"); // 👈
        }
    }