How to use SupportMapFragment inside a Fragment?

chkm8 picture chkm8 · Jul 31, 2014 · Viewed 27k times · Source

I know that there has been an issue in using a nested fragment. But my application was designed to run on fragments and if i will be using activity for the map, my casting functions will have error.

I would like to ask help from you on how to achieve this. I've been searching in the internet but i couldn't find best solution.

I've tried this code:

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) myFragmentActivity.getSupportFragmentManager().findFragmentById(R.id.map_con))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }
}

this would give me duplicate error because of R.id.map_con is a fragment inside my fragment.

So I look for a work around, this time, R.id.map_con is a frame layout and in the run time I created the SupportMapFragment to it.

SupportMapFragment mSupportMapFragment = new SupportMapFragment();
    myFragmentActivity.getSupportFragmentManager().beginTransaction()
            .replace(R.id.map_con, mSupportMapFragment).commit();

though this does not give me a duplicate every time a close and open the fragment. but my error is that mSupportMapFragment.getMap is always null., I don't get it why its null?.

mMap = mSupportMapFragment.newInstance().getMap();
        if (mMap != null){
            Log.e("ReportFragment","mMap is not empty");
        }else{
            Log.e("ReportFragment","mMap is empty");
        }

I would really appreciate any inputs from you guys, or do you have another work around but still in this process, i.e Fragment inside fragment

Thanks

chkm8

Answer

lpfx picture lpfx · Feb 11, 2017

getMap() is deprecated

The code should be something like this in a Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_location, container, false);

    mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mMapFragment.getMapAsync(this);

    return v;   
}