ChoiceSDK
ChoiceSDK copied to clipboard
Maps usage in Jetpack Compose
How can we use maps in Jetpack Compose? (I have no prior knowledge in XML based views). Thanks
I was able to get it working as follows:
Update app/build.gradle
dependencies {
// ...
implementation 'androidx.fragment:fragment-ktx:1.5.0'
implementation 'androidx.compose.ui:ui-viewbinding:1.1.1'
}
Add resources/layout/layout_map.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapFragmentContainerView"
android:name="at.bluesource.choicesdk.maps.common.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.fragment.app.FragmentContainerView>
Instantiate with View Binding anywhere in a @Composeable
Box {
AndroidViewBinding(
LayoutMapBinding::inflate,
modifier = Modifier.fillMaxSize()
) {
val mapFragment = mapFragmentContainerView.getFragment<MapFragment>()
mapFragment.getMapAsync {
it!!.moveCamera(
CameraUpdateFactory.get().newCameraPosition(
CameraPosition.Builder().setTarget(
LatLng(
10.7773886,
106.7114015
)
).build()
)
)
}
}
}
I also needed to extend AppCompatActivity()
instead of ComponentActivity()
.
One other note, my map is in a dialog, and the second time I opened the dialog the map didn't load. I found this workaround by experimentation:
// Inside AndroidViewBinding
mapFragmentContainerView.doOnAttach { it.doOnDetach { mapFragmentContainerView.removeAllViews() } }
Really wish Huawei would get on this and know that in the Android world libraries need constant updating to remain useful!