I have an app with navigation drawer with Google Maps fragment and some other fragments. I'm creating the SupportMapFragment
programmatically and putting it in my custom fragment_map
layout in map container.
The problem is I have to add more than 2000+ markers to the map from database but do not want to fill them again every time the device got rotated. I thought the setRetainInstance(true)
will solve the issue but it's not working — I'm getting a brand new map without markers and camera in 0, 0 position on orientation change. The sample apps are working fine with retained istance but they all are using FragmentActivity which is not my case. What is the problem with fragments here?
GoogleMapsFragment.java:
public class GoogleMapsFragment extends Fragment implements OnMapReadyCallback {
private SupportMapFragment mapFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
FragmentManager fm = getChildFragmentManager();
mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(this);
mapFragment.setRetainInstance(true);
fm.beginTransaction().add(R.id.map_cont, mapFragment).commit();
}
return rootView;
}
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions().position(new LatLng(5, 5)));
// a long code with map initialization and adding markers here
// ...
}
}