ChoiceSDK icon indicating copy to clipboard operation
ChoiceSDK copied to clipboard

Maps usage in Jetpack Compose

Open AkisArou opened this issue 2 years ago • 1 comments

How can we use maps in Jetpack Compose? (I have no prior knowledge in XML based views). Thanks

AkisArou avatar Mar 09 '22 12:03 AkisArou

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!

Queatz avatar Jul 01 '22 05:07 Queatz