getMapAsync() in Fragment

RussVirtuoso picture RussVirtuoso · Feb 19, 2016 · Viewed 40.8k times · Source

I having trouble implementing Google Map in Fragment.

This is my the part of my fragment class:

public class FragmentStoreFinderMap extends Fragment implements OnMapReadyCallback {

// Google Map
private GoogleMap googleMap;
private int i;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        googleMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(
              R.id.map)).getMapAsync(this);

I am getting an error in getMapAsync(this). I tells Incompatible type.

it says:

required: com.google.android.gms.map.GoogleMap

found: void

BTW here is my xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment 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"/>

</LinearLayout>

Answer

Lester L. picture Lester L. · Feb 19, 2016

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.