如何在片段中嵌入谷歌地图?
Posted
技术标签:
【中文标题】如何在片段中嵌入谷歌地图?【英文标题】:How Embed a Google Map inside a Fragment? 【发布时间】:2021-09-08 17:14:53 【问题描述】:我正在尝试将 Google 地图嵌入到属于另一个 Fragment 的 FragmentContainer 中。
这是我目前所拥有的(API 和凭据工作正常):
DetailsFragment.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_
android:layout_
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/property_layout" />
(...)
</layout>
Fragment 正确捕获了 Map Api,但未触发 OnMapReadyCallback,因此我无法设置位置和标记。此代码使用专用 Activity 工作,我尝试使用 Fragment 找到解决方案,但没有运气。这里有什么帮助吗?类型
【问题讨论】:
【参考方案1】: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
【讨论】:
以上是关于如何在片段中嵌入谷歌地图?的主要内容,如果未能解决你的问题,请参考以下文章