Skip to content

Tutorial_3

MKer edited this page Apr 25, 2021 · 8 revisions

(we assume you already followed Tutorial_1 and Tutorial_2)

10. Marker Clustering

Marker Clustering is a now classical technique when you have a lot of markers on a map, to group markers which are close together in a single "cluster" marker, displaying the number of markers it "contains".

This (cool) feature is available in OSMBonusPack with the RadiusMarkerClusterer.

If you already grouped your markers in a FolderOverlay (as we did in chapter 5 with poiMarkers), introducing marker clustering is trivial. You replace the FolderOverlay by a RadiusMarkerClusterer:

RadiusMarkerClusterer poiMarkers = new RadiusMarkerClusterer(this);

You also have to set an icon for the clusters. This is the icon to be used when there are many markers in a cluster. Android SDK making it more and more complex, here is a simple and safe way to get a Bitmap from a Drawable resource:

Bitmap clusterIcon = BonusPackHelper.getBitmapFromVectorDrawable(this, R.drawable.marker_cluster);

Then you can set this icon to clusters:

poiMarkers.setIcon(clusterIcon);

The rest of the code: adding the poiMarkers to map overlays, and adding markers to poiMarkers, has already been done in chapter 5, and need no change.

So you can give it a try.

The result when searching for "bakery" with NominatimPOIProvider:

If you zoom in, each individual marker appears. When you zoom out, they are grouped and displayed with the cluster icon. If you tap on a cluster icon, it automatically zoom in, fitting to the box of all included markers.

Fine, isn't it?

11. Customizing the clusters design - and beyond

11.1 Simple customization

To customize the design of clusters, the first level is to use the available getters, setters and public attributes.

Example:

poiMarkers.getTextPaint().setColor(Color.DKGRAY);
poiMarkers.getTextPaint().setTextSize(12 * getResources().getDisplayMetrics().density); //taking into account the screen density
poiMarkers.mAnchorU = Marker.ANCHOR_RIGHT;
poiMarkers.mAnchorV = Marker.ANCHOR_BOTTOM;
poiMarkers.mTextAnchorV = 0.40f;

11.2 Advanced customization

But you may want to go deeper. There is a lot of excellent ideas for cluster design:

  • circles with various colors or sizes,
  • set of photos,
  • ...

You can implement such designs by sub-classing the RadiusMarkerClusterer. Then you override #buildClusterMarker(StaticCluster cluster, MapView mapView) method, and you draw your cluster icon as needed.

To have a good starting point, you can look

  • at RadiusMarkerClusterer#buildClusterMarker source code
  • or at OSMBonusPackTuto CirclesGridMarkerClusterer, which implements circles with various colors and sizes.

If you want to go further, you can also implement your own clustering algorithm. You "just" have to sub-class the MarkerClusterer, and override the #clusterer(MapView mapView) method.

Next step

In Tutorial_4, you will learn how to use the KML and GeoJSON toolbox.