Google Map with Marker Clustering

Datetime:2017-04-18 05:18:07         Topic: Cluster Analysis  Andrew Development          Share        Original >>
Here to See The Original Article!!!

https://tinyurl.com/mtej4pu

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.

How do I get clustering in my app?

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 'com.google.maps.android:android-maps-utils:0.5'

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();   
mClusterManager.cluster();

The addPersonItems function:

private void addPersonItems() {                        mClusterManager.addItem(new Person(-26.187616, 28.079329, "PJ", "https://twitter.com/pjapplez"));   
}

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:

https://github.com/pjwelcome/GoogleMapsTutorial

Let me know what you think in the comments.

Get in Touch!








New