android 如何在Fragment类中显示GoogleMapsMap及其功能?

u3r8eeie  于 2023-04-10  发布在  Android
关注(0)|答案(1)|浏览(118)

我有一个Mainactivity,它有一个底部导航菜单,我可以在其中的一个片段中切换。在其中的一个片段中,我有一个主页片段,我应该用一个简单的标记来可视化Map。
我的问题是为什么谷歌Map不更新摄像头到指定的固定位置?我应该实现另一个类来扩展SupportMapFragment以正确地可视化Map吗?
下面是我的代码:首页.kt

class HomepageFragment : Fragment(), GoogleMap.OnMyLocationButtonClickListener,
    GoogleMap.OnMyLocationClickListener, OnMapReadyCallback {

    private lateinit var map: GoogleMap
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val mapFragment = childFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment?
       mapFragment?.getMapAsync(this)
        return inflater.inflate(R.layout.fragment_homepage, container, false)
    }

    override fun onMyLocationButtonClick(): Boolean {
        // TODO something
        return false
    }

    override fun onMyLocationClick(location: Location) {
        // TODO something
    }

    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap
        map.setOnMyLocationButtonClickListener(this)
        map.setOnMyLocationClickListener(this)

        val fixedPosition: LatLng = LatLng(40.1234, 13.1234)
        map.addMarker(
            MarkerOptions()
                .position(fixedPosition)
                .title("My fixed position")
        )
        map.moveCamera(CameraUpdateFactory.newLatLng(fixedPosition))
    }

}

fragment_homepage.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.HomepageFragment">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/map_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</androidx.constraintlayout.widget.ConstraintLayout>

结果enter image description here
我所期望的enter image description here

deyfvvtc

deyfvvtc1#

错误出现在以下行中:

val mapFragment = childFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment?
 mapFragment?.getMapAsync(this)
 return inflater.inflate(R.layout.fragment_homepage, container, false)

你必须改变这些:

val view : View = inflater.inflate(R.layout.fragment_homepage, container, false)
val mapFragment = childFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment?
mapFragment?.getMapAsync(this)
return view

相关问题