googlemaps / android-maps-compose

Jetpack Compose composables for the Maps SDK for Android
https://developers.google.com/maps/documentation/android-sdk/maps-compose
Apache License 2.0
1.14k stars 135 forks source link

How to show images downloaded from network efficiently? #210

Open shafayatb opened 1 year ago

shafayatb commented 1 year ago

Basically what I am doing is downloading the images from server and making an icon with the icon generator. After all the icons has been fully generated then I am putting the markers in the map. But from large list of markers it will take too much time to draw the markers. So how to do this in an optimized way?

fun CustomMarker(
    blipsList: List<Blip>,
    iconMap: MutableMap<String, Bitmap>,
    hasImageLoaded: Boolean,
    event: (HomeEvents) -> Unit,
    markerClick: (blipId: String) -> Unit
) {
    val context = LocalContext.current
    val iconGenerator = IconGenerator(context)
    val inflatedView = View.inflate(context, R.layout.custom_marker, null)
    val userImage = inflatedView.findViewById<ImageView>(R.id.userImageView)

    iconGenerator.setBackground(null)
    iconGenerator.setContentView(
        inflatedView
    )
    for (blip in blipsList) {
        Glide.with(LocalContext.current)
            .asDrawable()
            .circleCrop()
            .load("${Constants.BASE_URL}${blip.user.photo}")
            .into(object : CustomTarget<Drawable>() {
                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    val resource =
                        AppCompatResources.getDrawable(context, R.drawable.person)?.toBitmap()
                    val circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(context.resources, resource)
                    circularBitmapDrawable.isCircular = true
                    userImage.setImageDrawable(circularBitmapDrawable)
                    iconMap[blip.id] = iconGenerator.makeIcon()
                    if (iconMap.size == blipsList.size) {
                        event(
                            HomeEvents.UserImageLoadedEvent(
                                true
                            )
                        )
                    }
                }

                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    userImage.setImageDrawable(resource)
                    iconMap[blip.id] = iconGenerator.makeIcon()
                    if (iconMap.size == blipsList.size) {
                        event(
                            HomeEvents.UserImageLoadedEvent(
                                true
                            )
                        )
                    }
                }

                override fun onLoadCleared(placeholder: Drawable?) {

                }

            })
    }
    if (hasImageLoaded) {
        for ((i, blip) in blipsList.withIndex()) {
            Marker(
                state = MarkerState(
                    LatLng(blip.lat, blip.lng)
                ),
                icon = BitmapDescriptorFactory.fromBitmap(
                    iconMap[blip.id] ?: iconGenerator.makeIcon()
                ),
                tag = i,
                onClick = { mark ->
                    Log.v("Blip", blipsList[mark.tag as Int].id)
                    markerClick.invoke(blipsList[mark.tag as Int].id)
                    return@Marker true
                }
            )
        }
    }
}

I tried to recompose the markers each time the image is downloaded but it got stuck in infinite recompose.

shafayatb commented 1 year ago

Use clustering

How will clustering help in this situation?

ek868 commented 1 year ago

I have this exact same issue.

Did you end up finding any solutions?

shafayatb commented 1 year ago

No. Enabled disk caching so next time it won't take much time. Also i am not using large images in the markers.

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. Please comment here if it is still valid so that we can reprioritize. Thank you!

cwsiteplan commented 10 months ago

rendering async images is still a problem i think. also see recent discussion in https://github.com/googlemaps/android-maps-compose/issues/385

cwsiteplan commented 10 months ago

using a key to trigger re-composition of the marker when the image is loaded does not work for me. (using coil)

var showImage by remember {
    mutableStateOf(false)
}

val painter = rememberAsyncImagePainter(
    model = ImageRequest.Builder(LocalContext.current)
        .data("https://www.aquasafemine.com/wp-content/uploads/2018/06/dummy-man-570x570.png")
        .size(Size.ORIGINAL) // Set the target size to load the image at.
        .build()
)

if (painter.state is AsyncImagePainter.State.Success) {
    showImage = true
}

MarkerComposable(
    keys = arrayOf(showImage),
    state = singapore4State,
) {
    Image(
        painter = painter,
        contentDescription = "asdf"
    )

}
leinardi commented 8 months ago

I've found out that using clustering plus the NonHierarchicalViewBasedAlgorithm as algorithm for the ClusterManager helps since it will render the images only for unclustered items that are visible on the screen.

    var mapSize by remember { mutableStateOf(IntSize.Zero) }

    GoogleMap(
        modifier = Modifier
            .fillMaxSize()
            .onGloballyPositioned { mapSize = it.size },
        cameraPositionState = cameraPositionState,
    ) {
        val coroutineScope = rememberCoroutineScope()
        if (!state.mapItems.isNullOrEmpty()) {
            val clusterManager = rememberClusterManager<CollaboratorsMapItem>()
            val renderer = rememberClusterRenderer(
                clusterContent = null,
                clusterItemContent = { item ->
                    AndroidView(
                        factory = { context ->
                            ImageView(context).apply {
                                scaleType = ImageView.ScaleType.CENTER_CROP
                                layoutParams = ViewGroup.LayoutParams(56.toPxSize, 56.toPxSize)
                                load(item.collaborator.imageUrl) {
                                    allowHardware(false)
                                    crossfade(false)
                                    error(com.veeva.link.library.ui.R.drawable.ui_img_default_profile)
                                    fallback(com.veeva.link.library.ui.R.drawable.ui_img_default_profile)
                                    placeholder(com.veeva.link.library.ui.R.drawable.ui_img_default_profile)
                                }
                            }
                        },
                        modifier = Modifier
                            .size(56.dp)
                            .border(3.dp, MaterialTheme.colorScheme.surface.copy(alpha = ContentAlpha.medium), CircleShape)
                            .padding(3.dp)
                            .clip(CircleShape),
                    )
                },
                clusterManager = clusterManager,
            )
            SideEffect {
                clusterManager ?: return@SideEffect
                clusterManager.algorithm = NonHierarchicalViewBasedAlgorithm(mapSize.width.toDp.roundToInt(), mapSize.height.toDp.roundToInt())
            }
            SideEffect {
                if (clusterManager?.renderer != renderer && renderer != null) {
                    (renderer as DefaultClusterRenderer).minClusterSize = 2
                    clusterManager?.renderer = renderer
                }
            }

            if (clusterManager != null) {
                Clustering(
                    items = state.mapItems,
                    clusterManager = clusterManager,
                )
            }
        }
    }

image