Thanks to @JJD, I wrote the same in Kotlin.
private var selectedBitmap: BitmapDescriptor? = null
private var unselectedBitmap: BitmapDescriptor? = null
private var lastMarker: Marker? = null
private var clusterManager: ClusterManager<StationClusterItem>? = null
override fun onMapReady(googleMap: GoogleMap) {
this.googleMap = googleMap
clusterManager = ClusterManager(context!!, googleMap)
val clusterRenderer = MarkerClusterRenderer(context!!, googleMap, clusterManager!!,
unselectedBitmap!!)
clusterManager!!.renderer = clusterRenderer
// Add your items to the ClusterManager here with clusterManager?.addItem().
// Better is in background thread.
val boundsBuilder = LatLngBounds.Builder()
...
clusterManager!!.cluster()
// Add this listener to make ClusterManager correctly zoom clusters and markers.
googleMap.setOnCameraIdleListener(clusterManager)
// This method is needed to use setOnClusterItemClickListener.
googleMap.setOnMarkerClickListener(clusterManager)
clusterManager!!.setOnClusterItemClickListener { item ->
lastMarker?.setIcon(unselectedBitmap)
lastMarker = clusterRenderer.getMarker(item) // Here we access a selected marker.
lastMarker?.setIcon(selectedBitmap)
// false - to show info window. See GoogleMap.InfoWindowAdapter.
// true - to hide info window.
false
}
}
class MarkerClusterRenderer(
val context: Context,
val map: GoogleMap,
clusterManager: ClusterManager<StationClusterItem>,
private val markerBitmap: BitmapDescriptor
) : DefaultClusterRenderer<StationClusterItem>(context, map, clusterManager) {
init {
minClusterSize = 1 // 2, 3 or more, as you wish.
}
override fun onBeforeClusterItemRendered(item: StationClusterItem?,
markerOptions: MarkerOptions?) {
super.onBeforeClusterItemRendered(item, markerOptions)
markerOptions?.icon(markerBitmap)
}
}
UPDATE
I got an exception: java.lang.IllegalArgumentException: Unmanaged descriptor
when clicked markers (in a line lastMarker?.setIcon(unselectedBitmap)
).
After studying IllegalArgumentException: Unmanaged descriptor using gms.maps.model.Marker.setIcon I rewrote that listener:
private var selectedItem: StationClusterItem? = null
clusterManager!!.setOnClusterItemClickListener { item ->
if (selectedItem != null) {
// Set here a reference to a previous marker.
// We save a reference to a previous item, not to a marker.
val lastMarker = clusterRenderer.getMarker(selectedItem)
lastMarker?.setIcon(unselectedBitmap)
}
selectedItem = item
// Now get a reference to a selected marker.
val newMarker = clusterRenderer.getMarker(item)
newMarker?.setIcon(selectedBitmap)
false
}