Sunday 23 August 2020

Kotlin for Android: setting a Google Maps marker image to a URL

I'd like to set a marker on a Google Map displayed by an Android Kotlin app to be a URL of my choice. It's clear that fetching the URL content needs to be done off the UI thread, and that coroutines are the approach here, so I'd like to run a few lines of code to fetch the URL and put it into a BitmapDescription object inside a coroutine, and then use that BitmapDescription to call setIcon on the Marker object to set the custom image.

I already have a Marker, and a URL. So I tried this:

    uiScope.launch(Dispatchers.IO) { // not sure this is the best way to launch in IO
        val furl = URL(myURL)
        val bm = BitmapFactory.decodeStream(furl.openConnection().getInputStream())
        val bd = BitmapDescriptorFactory.fromBitmap(bm)
        uiScope.launch(Dispatchers.Main) { // go back to UI thread; this crashes
            marker.setIcon(bd)
        }
    }

This is obviously not right because it crashes. The fetch of the URL and creating a BitmapDescriptor seems to be working fine as far as I can tell; once I have that BitmapDescriptor, how do I call marker.setIcon with it?



from Kotlin for Android: setting a Google Maps marker image to a URL

No comments:

Post a Comment