Google Map with Marker Clustering

Have you ever used a map with so many markers on it, that it was impossible to select the pin of interest? If only the pins in close proximity could be grouped together to make the map more user-friendly. This is known as Clustering, and yes it can be done.

Clustering on Google Maps is really simple because there is an awesome library that helps us do this. The Google Maps Utils library.

Note: This is assuming you have already set up a Google Map in your Android app. If not, then visit Google Maps API to get started.

To get this library, all we need to do is add it as a dependency in our build.gradle.

compile ''

Once that’s done, we need to implement an interface called ClusterItem on our model class. This interface will provide marker data to our model.

public class Person implements ClusterItem

ClusterItem provides us with three methods that we need to implement:

  1. LatLng getPosition()
  2. String getTitle()
  3. String getSnippet()

This will make our model conform to what we need for the cluster manager, which is what we will look at next.

In our Activity, we create a ClusterManager variable of the same Type as our model.

private ClusterManager<Person> mClusterManager;

Then in our onMapReady method (or wherever you have access to your GoogleMap object):

  1. Initialize our ClusterManager.
  2. Set the ClusterManager to the relevant listeners on the GoogleMap object.
  3. Add Items, which are our markers, to the ClusterManager.
  4. Finally ask the ClusterManager to cluster our markers.

Yes, that sounds like a lot of work but as we can see below, it’s just a few lines of code.

mClusterManager = new ClusterManager<>(this, googleMap);
googleMap.setOnCameraIdleListener(mClusterManager); googleMap.setOnMarkerClickListener(mClusterManager); googleMap.setOnInfoWindowClickListener(mClusterManager); addPersonItems();

The addPersonItems function:

private void addPersonItems() {                        mClusterManager.addItem(new Person(-26.187616, 28.079329, "PJ", ""));   

And there you go, you have clustering on your Google Map Activity!

Google Maps with Clustering Markers

There is so much more you can do with clustering, and Google Maps.

Stay tuned for more on Google Maps.

For a more complete example of the above code, you can visit my Github page:

Let me know what you think in the comments.

Get in Touch!

Peter John Welcome — Google+

Thanks to Ashton Welcome and Joshua Leibstein for reviewing this post.

Freelance Senior Mobile Engineer, Google Developer Expert for Firebase, Photographer

The (retired) Pub(lication) for Android & Tech, focused on Development