Search code examples
javaandroidgoogle-mapsgoogle-maps-android-api-2android-maps-utils

Disable clustering at max zoom level with Googles android-maps-utils


I'm clustering markers on a Google map in Android using the clustering from android-maps-utils. I want to disable the clustering when the map is at it's max zoom level (ie always render individual ClusterItems if the map is at max zoom level, otherwise cluster as normal).

I'm able to almost get it working by doing a test for zoom level in shouldRenderAsCluster() in a custom class extending DefaultClusterRenderer. However my solution lags one step behind the actual zoom level. For instance if the max zoom for the map is level 21, and the user zooms in from level 20 to level 21, the check in shouldRenderAsCluster will get a current zoom level of 20. If the user then zooms out to level 20 the check will get level 21. The ClusterItems gets rendered as individual items like I want, but one zoom action too late.

I get the "Current Zoom" (which is not really current apparently) from the variable mZoom that is set in DefaultClusterRenderer.

This is the code:

public class UserClusterRenderer extends PosMapDefaultClusterRenderer<UserClusterItem> {

    // ...

    @Override
    protected boolean shouldRenderAsCluster(Cluster cluster) {
        return mZoom < mMap.getMaxZoomLevel() && cluster.getSize() > 1;
    }
}

The variables mZoom and mMap are set in DefaultClusterRenderer. Because they have private access there I've made a copy of DefaultClusterRenderer called PosMapDefaultClusterRenderer. The only difference is that mZoom and mMap are declared protected instead so they're accessible in UserClusterRenderer.

Why is mZoom lagging one zoom action behind? Is there a way to get the real zoom level for which the clusters are being rendered?

The zooming is done with a call to animateCamera using a cameraUpdate from a cameraPosition.

Also this is my first question on StackOverflow so any input on tags, formatting etc is welcome.

Edit: Working code after Vai's answer:

public class UserClusterRenderer extends DefaultClusterRenderer<UserClusterItem> {

    GoogleMap mMapCopy; // Store a ref to the map here from constructor

    // ...

    @Override
    protected boolean shouldRenderAsCluster(Cluster cluster) {
        float currentZoom = mMapCopy.getCameraPosition().zoom;
        float currentMaxZoom = mMapCopy.getMaxZoomLevel();
        return currentZoom < currentMaxZoom && cluster.getSize() > 1;
    }
}

Solution

  • You don't need to copypaste the whole class to get mZoom. You can get the current zoom (not lagged, I hope) using:

    mMap.getCameraPosition().zoom
    

    Your approach of shouldRenderAsCluster() looks correct. Let me know if this doesn't work and we'll check it out. Welcome to SO.