Using Google Maps inside a Fragment in Android

女生的网名这么多〃 提交于 2019-12-01 12:44:26

line 66 of your MapsFragment, replace:

// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map))
    .getMap();

by:

// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map))
    .getMap();

Because your map fragment is a fragment in a fragment, and not managed by the top level FragmentManager.

Also, I am not sure but you may want to setup your Map asynchronously:

    ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMapAsync(
    new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            setUpMap();
        }
    });

You can do this as a normal fragment.

public void replaceFragment(Fragment fragment, String fragmentTag){
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, fragment);
            fragmentTransaction.addToBackStack(fragmentTag);
            fragmentTransaction.commit();
        }

private void initMap(){
        MapFragment mapFragment = MapFragment.newInstance();
        replaceFragment(mapFragment, fragmentTag);
        mapFragment.getMapAsync(this);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!