Carlos Jiménez
Carlos Jiménez

Reputation: 158

How Embed a Google Map inside a Fragment?

I'm trying to embed a Google Map inside a FragmentContainer which is part of another Fragment.

This is what I have so far (API and credentials are working fine):

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_width="match_parent"
                android:layout_height="250dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/property_layout" />

(...)

</layout>

The Fragment captures correctly the Map Api but the OnMapReadyCallback is not being triggered, so I cannot set a position and marker. This code works using a dedicated Activity, I've tried to find a solution using a Fragment, but no luck. Any help here? Ty

Upvotes: 1

Views: 63

Answers (1)

Muhammad Zahab
Muhammad Zahab

Reputation: 1105

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
    }

Upvotes: 1

Related Questions