Home > database >  Cannot load Google map in Kotlin Fragment?
Cannot load Google map in Kotlin Fragment?

Time:09-26

I need to load a google map into fragment. Here's my code and it's not working.

class busFragment : Fragment(), OnMapReadyCallback{

    private lateinit var mMap: GoogleMap

    companion object {
        var mapFragment : SupportMapFragment?=null
        val TAG: String = busFragment::class.java.simpleName
        fun newInstance() = busFragment()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        var rootView = inflater.inflate(R.layout.fragment_bus, container, false)

        childFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)

        return rootView
    }

    override fun onMapReady(googleMap: GoogleMap?) {
        mMap = googleMap!!
    }

}

I added meta tag, dependencies in gradle and manifest. also give internet permission.

<meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR_API_KEY"/>
 <uses-permission android:name="android.permission.INTERNET" />
implementation 'com.google.android.gms:play-services-maps:17.0.1'

Here's my xml file of that fragment. In this I used map view.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="busFragment">

    <!-- TODO: Update blank fragment layout -->

    <com.google.android.gms.maps.MapView
        android:id="@ id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="-1dp"
        tools:layout_editor_absoluteY="114dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

CodePudding user response:

This is because mapFragment does not initialize.

Replace this

childFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
mapFragment?.getMapAsync(this)

With this

mapFragment = childFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
mapFragment?.getMapAsync(this)
  • Related