getMapAsync() in Fragment

After a few overheats in my head, thanks to this post and https://stackoverflow.com/a/34732804/3925554, I would say that currently there are two ways of adding a MapFragment to your app:

<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
class="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

By this way, you have to use a standard fragment and implement this inside. Actually you are inserting a fragment into another:

    @Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    
    SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    supportMapFragment.getMapAsync(this);
}

The other way would be extending the real SupportMapFragment and implement it in this manner without the need of an xml:

    @Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    getMapAsync(this);
}

And they work without having to set a layout in onCreateView neither call mapView.onCreate(savedInstanceState); and mapView.onResume(); manually inside onViewCreated(), what is not recommended anyway.

Hope it helps!


In your XML layout you should do like this

<FrameLayout 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">

<com.google.android.gms.maps.MapView
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</FrameLayout>

inside your fragment implement this

private MapView mapView;
private GoogleMap googleMap;

override onCreateView if there is no onCreateView just like the code below

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.your_layout, container, false);
}

override onViewCreated() inside that onViewCreated() put this

mapView = (MapView) view.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(this);//when you already implement OnMapReadyCallback in your fragment

when you already implement OnMapReadyCallback in your fragment put this/code like this

@Override
public void onMapReady(GoogleMap map) {
    googleMap = map;
}

hope this helps you.