If you use Clusters
, a behaviour is slightly different.
Looking at https://medium.com/@yilmazvolkan/custom-map-marker-8b136212d766 and here, I wrote so.
styles.xml:
<!-- Google Maps marker -->
<style name="MarkerText">
<item name="android:textSize">12sp</item>
<item name="android:textColor">#f0f0f0</item>
</style>
marker_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="#3232a0" />
<corners android:radius="18dp" />
</shape>
Fragment:
private var clusterManager: ClusterManager<SomeClusterItem>? = null
private var clusterRenderer: MarkerClusterRenderer<SomeClusterItem>? = null
private var unselectedBitmap: BitmapDescriptor? = null
private var iconGenerator: IconGenerator? = null
private var selectedItem: SomeClusterItem? = null
override fun onMapReady(googleMap: GoogleMap) {
this.googleMap = googleMap
...
unselectedBitmap =
BitmapUtils.bitmapDescriptorFromVector(context!!, R.drawable.unselected_item)
// Create a text marker background.
iconGenerator = IconGenerator(context!!)
iconGenerator!!.setTextAppearance(R.style.MarkerText)
val markerBackground = ContextCompat.getDrawable(context!!, R.drawable.marker_bg)
iconGenerator!!.setBackground(markerBackground)
clusterManager = ClusterManager(context!!, googleMap)
clusterRenderer = MarkerClusterRenderer(context!!, googleMap, clusterManager!!,
unselectedBitmap!!)
clusterManager!!.renderer = clusterRenderer
...
// Create a list of markers.
val boundsBuilder = LatLngBounds.Builder()
...
// Show clusters and markers.
clusterManager!!.cluster()
clusterManager!!.setOnClusterItemClickListener { item ->
// Deselect selected marker.
// See https://mcmap.net/q/658634/-how-to-change-the-clicked-marker-icon-using-android-maps-utils.
if (selectedItem != null) {
deselectMarker(selectedItem)
}
selectedItem = item
selectMarker(selectedItem!!, iconGenerator)
// Show info window. See GoogleMap.InfoWindowAdapter.
false
}
clusterManager!!.setOnClusterClickListener {
deselectMarker(selectedItem)
true
}
private fun selectMarker(item: SomeClusterItem,
iconGenerator: IconGenerator) {
// Generate a text marker.
val icon = iconGenerator.makeIcon(item.title)
val bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(icon)
clusterRenderer?.getMarker(item)?.setIcon(bitmapDescriptor)
}
private fun deselectMarker(item: SomeClusterItem?) =
clusterRenderer?.getMarker(item)?.setIcon(unselectedBitmap)
Then you will see these pictures (all items are not selected and one item is selected).
Note that InfoWindow is shown. To customize info window, see https://mcmap.net/q/265603/-android-google-maps-v2-how-to-add-marker-with-multiline-snippet.
To remove info window, just return true
in an appropriate method (see Hide markers info window in android google maps API v2).
clusterManager!!.setOnClusterItemClickListener { item ->
...
true
}