android-maps-compose icon indicating copy to clipboard operation
android-maps-compose copied to clipboard

How to show images downloaded from network efficiently?

Open shafayatb opened this issue 3 years ago • 7 comments

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 avatar Sep 29 '22 17:09 shafayatb

Use clustering

How will clustering help in this situation?

shafayatb avatar Sep 30 '22 08:09 shafayatb

I have this exact same issue.

Did you end up finding any solutions?

ek868 avatar Oct 25 '22 00:10 ek868

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

shafayatb avatar Oct 25 '22 03:10 shafayatb

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!

stale[bot] avatar Jun 18 '23 08:06 stale[bot]

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

cwsiteplan avatar Nov 06 '23 07:11 cwsiteplan

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"
    )

}

cwsiteplan avatar Nov 06 '23 07:11 cwsiteplan

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

leinardi avatar Dec 14 '23 14:12 leinardi