'How to add onMapRedy to Fragment?

I am trying to initialize google maps in a fragment. To test, I'm trying to call the standard code from onMapRead, which should center the camera and place a label in Sydney.

class FirstFragment : Fragment(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

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

    val mapFragment = parentFragmentManager
        .findFragmentById(R.id.first_map) as? SupportMapFragment
    mapFragment?.getMapAsync(this)

}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_first, container, false)

}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(-34.0, 151.0)
    mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}

} But it doesn't happen when the app starts.



Solution 1:[1]

The issue is resolved, it is necessary to initialize the map in onCreateView, here is my code for those who also face this problem

class FirstFragment : Fragment(), OnMapReadyCallback{

private lateinit var mMap: GoogleMap

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val view = inflater.inflate(fragment_first, container, false)

    val mapFragment = childFragmentManager
        .findFragmentById(R.id.first_map) as? SupportMapFragment
    mapFragment?.getMapAsync(this)

    return view
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(-34.0, 151.0)
    mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lian. lun