In my Android app, I am displaying 1000s of markers on Google Maps, I am caching the BitmapDescriptor of each marker.
Is it a good approach to cache Bitmap Descriptor? If yes, am I doing it correctly?
When displaying a large amount of markers, the UI kind of lags
object MarkerIconCache {
// Cache size based on typical number of unique marker types you expect
private const val CACHE_SIZE = 1000
data class MarkerKey(
val number: String,
val date: String
)
private val iconCache = object : LruCache<MarkerKey, BitmapDescriptor>(CACHE_SIZE) {
override fun entryRemoved(
evicted: Boolean,
key: MarkerKey,
oldValue: BitmapDescriptor,
newValue: BitmapDescriptor?
) {
// Clean up bitmap resources when removed from cache
oldValue.let {
if (it is BitmapDescriptor) {
// Optional: Release any resources if needed
}
}
}
}
fun clearCache() {
iconCache.evictAll()
}
fun getMarkerIcon(context: Context, data: MapUI): BitmapDescriptor {
// Cache key based only on color since the bitmap really only varies by color
val key = MarkerKey(
number = data.name,
date = data.Date
)
return iconCache.get(key) ?: createRectangleMarkerBitmap2(
context = context,
text = data.number,
).also {
iconCache.put(key, it)
}
}
}
Usage in composable
@Composable
fun MapMarkers(
mapViewModel: MapVM,
) {
val mapData by mapViewModel.markerData.collectAsStateWithLifecycle()
val context = LocalContext.current
//getting bitmap from cache
val markerIcons = remember(mapData) {
mapData.associateWith { data-> getMarkerIcon(context, data) }
}
//this function adjust markers if they are in same place
val adjustedMarkers = remember(mapData) { createAdjustedMarkers(mapData) }
adjustedMarkers.forEach { (data, position) ->
val markerState = MarkerState(position = position)
Marker(
state = markerState,
icon = markerIcons[data] )
}
}
You need to sign in to view this answers
Leave feedback about this