A fast marker clustering library for Google Maps Android API.
Why not use Google Maps Android API Utility Library? Because it's very slow for large amounts of markers.
- Implement
ClusterItemto represent a marker on the map. The cluster item returns the position of the marker and an optional title or snippet:
class SampleClusterItem implements ClusterItem {
private final LatLng location;
SampleClusterItem(@NonNull LatLng location) {
this.location = location;
}
@Override
public double getLatitude() {
return location.latitude;
}
@Override
public double getLongitude() {
return location.longitude;
}
@Nullable
@Override
public String getTitle() {
return null;
}
@Nullable
@Override
public String getSnippet() {
return null;
}
}- Create an instance of ClusterManager and set it as a camera idle listener using
GoogleMap.setOnCameraIdleListener(...):
ClusterManager<SampleClusterItem> clusterManager = new ClusterManager<>(context, googleMap);
googleMap.setOnCameraIdleListener(clusterManager);- To add a callback that's invoked when a cluster or a cluster item is clicked, use
ClusterManager.setCallbacks(...):
clusterManager.setCallbacks(new ClusterManager.Callbacks<SampleClusterItem>() {
@Override
public boolean onClusterClick(@NonNull Cluster<SampleClusterItem> cluster) {
Log.d(TAG, "onClusterClick");
return false;
}
@Override
public boolean onClusterItemClick(@NonNull SampleClusterItem clusterItem) {
Log.d(TAG, "onClusterItemClick");
return false;
}
});-
To customize the icons create an instance of
IconGeneratorand set it usingClusterManager.setIconGenerator(...). You can also use the default implementationDefaultIconGeneratorand customize the style of icons usingDefaultIconGenerator.setIconStyle(...). -
Populate ClusterManager with items using
ClusterManager.setItems(...):
List<SampleClusterItem> clusterItems = generateSampleClusterItems();
clusterManager.setItems(clusterItems);