OnMapReady is not being called/shown in fragmentContainerView

Viewed 68

I'm new to Google Maps API, I have this problem that when I try to show the map on a fragmentContainerView it doesn't show the markers and doesn't zoom the camera but when I setContentView on the fragment itself it shows the markers zooms the camera.

This just shows the map inside the fragmentContainerView without the markers and doesn't zoom, it basically just calls a map.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_map)
        supportActionBar?.hide()

        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)
        
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    } 

Now this on the other hand shows the markers and zooms as well, but it replaces the whole activity view because of the setContentView.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_map)
        supportActionBar?.hide()

        binding = FragmentMapsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    }

Please Help.

1 Answers

The problem is that you're trying to use the Activity's FragmentManager, and you should be using the Fragment's child FragmentManager. Remove the onCreate() override in the Fragment, and add an onCreateView() Override where you inflate the layout.

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

    binding = FragmentMapsBinding.inflate(inflate,R.layout.activity_map, 
              container, false)


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

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    
    return binding.root
}
Related