https://kotlinlang.org logo
#compose
Title
# compose
m

Madhava

07/14/2020, 3:00 AM
I am trying to get a MapView going but I think I am misunderstanding which classes to use with AndroidView and how they work exactly. For maps, it seems like all the examples bind a MapView and a GoogleMap instance to an activity? I don't know how I can construct a MapView and connect it to a GoogleMap object in this AndroidView type pattern. Any help would be greatly appreciated. 🙂
Copy code
AndroidView(
    modifier = Modifier.fillMaxWidth().fillMaxHeight(),
    view = MapComponent(ctx, options)
)

// the getMapAsync never runs
private fun MapComponent(ctx: Context, options: GoogleMapOptions) = MapView(ctx, options).apply {
    val result = ctx.checkCallingPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    Log.i("MapView", "got permission check value: $result")

    val builder = LatLngBounds.Builder()
    val cameraUpdate = CameraUpdateFactory.newLatLngBounds(builder.build(), 0)

    getMapAsync {
        Log.i("MapView", "Does this run?")
        it.uiSettings.isMyLocationButtonEnabled = true
        it.isMyLocationEnabled = true
        it.mapType = MAP_TYPE_NORMAL
    }
}

// if i try it this way, I don't see how to get a view from a fragment
private fun MapComponent(ctx: Context, options: GoogleMapOptions) = SupportMapFragment.newInstance(options).getMapAsync { 
    
}
m

Mihai Popa

07/14/2020, 11:22 AM
Hmm, it seems to work if you do via XML:
Copy code
<androidx.fragment.app.FragmentContainerView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.google.android.gms.maps.SupportMapFragment">
    </androidx.fragment.app.FragmentContainerView>
and
Copy code
AndroidView(resId = R.layout...., postInflationCallback = { view ->
                val fragment = (view.context as AppCompatActivity).supportFragmentManager
                    .findFragmentById(R.id.map)

                (fragment as SupportMapFragment).getMapAsync { map ->
                    ...
                }
            })
👍 1
m

Madhava

07/15/2020, 12:16 AM
Thanks for the help, that works great! Glad to know how the fallback xml pattern works. 🙂
m

Mahdi

11/05/2020, 6:24 AM
@Mihai Popa Seems
Copy code
AndroidView(resId = R.layout...., postInflationCallback = { view ->
                val fragment = (view.context as AppCompatActivity).supportFragmentManager
                    .findFragmentById(R.id.map)

                (fragment as SupportMapFragment).getMapAsync { map ->
                    ...
                }
            })
Is not working in 06 version.
m

Mihai Popa

11/05/2020, 12:14 PM
We no longer offer the API for XML inflation. You should use the ViewBinding-based API instead:
Copy code
AndroidViewBinding(MyLayoutBinding::inflate) {
   val fragment = ...
}
10 Views