如何在片段中嵌入谷歌地图



我正试图将谷歌地图嵌入另一个Fragment的FragmentContainer中。

到目前为止,这就是我所拥有的(API和证书运行良好(:

细节发票.kt

class DetailsFragment : Fragment() {
private var binding: DetailsFragmentBinding? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
val fragmentBinding = DetailsFragmentBinding.inflate(inflater)
binding = fragmentBinding
return fragmentBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.apply {
lifecycleOwner = viewLifecycleOwner         
}
val mapFragment = fragmentManager?.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(callback)
}
private val callback = OnMapReadyCallback { googleMap ->
val sydney = LatLng(-34.0, 151.0)
googleMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}

details_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
(...)
<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="250dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/property_layout" />
(...)
</layout>

Fragment正确捕获了Map Api,但没有触发OnMapReadyCallback,因此我无法设置位置和标记。这段代码使用一个专用的"活动"来工作,我曾试图使用Fragment找到一个解决方案,但没有成功。这里有人帮忙吗?Ty

class MapsFragment : Fragment(), OnMapReadyCallback {
private var mMap: GoogleMap? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle
): View? {
val mView: View = inflater.inflate(R.layout.activity_maps, container, false)
val mapFragment: SupportMapFragment =
childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
return mView
}
fun onMapReady(googleMap: GoogleMap?) {
mMap = googleMap
}

最新更新