yanozai
yanozai

Reputation: 153

How to implement google maps in a Fragment correctly?

I have searched on stackoverflow and looked at so many solutions for example, here

here

I have looked at more but none of them robust in terms of performance. Here is what I got so far

This one works but only once when the fragment first created but then after returning to the map fragment it gives me layout inflation exception

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    view=inflater.inflate(R.layout.fragment_public_maps,null,false);
    googleMap= (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.pub_map);
    googleMap.getMapAsync(this);
    return view;
}

I have tried this one also and it works but it makes my app slow and sometimes it crashes

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    try
    {
        view=inflater.inflate(R.layout.fragment_public_maps,null,false);

    }
    catch (InflateException e)
    {
        googleMap= (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.pub_map);
        googleMap.getMapAsync(this);
        return view;
    }
    googleMap= (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.pub_map);
    googleMap.getMapAsync(this);
    return view;

}

I don't know what else to do if anyone can point me to the right direction I would really appreciate it.

Upvotes: 0

Views: 86

Answers (1)

eclipse1203
eclipse1203

Reputation: 635

The way I do it and it works great is to place a FrameLayout within your fragments xml file like so:

<FrameLayout
    android:id="@+id/map_id"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Then in your fragments onActivityCreated method you do this:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mMapFragment = MapFragment.newInstance();
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
        getChildFragmentManager().beginTransaction().replace(R.id.map_id, mMapFragment).commit();
    } else {
        getFragmentManager().beginTransaction().replace(R.id.map_id, mMapFragment).commit();
    }
    mMapFragment.getMapAsync(this);
}

If you're using support fragments,

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mMapFragment = SupportMapFragment.newInstance();
    getSupportFragmentManager().beginTransaction().replace(R.id.sod_map_lite, mMapFragment).commit();
}

Upvotes: 1

Related Questions