I am developing an app using the google maps android api. The app displays various tileoverlays that the user can turn on and off. When I rotate my device the overlay remains in place but when I click the button to turn off my overlay my device acts as if the variable that controls my overlay is null. How can I retain control over my tileoverlay under these circumstances.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
//mMap=null;
if (savedInstanceState == null) {
// First incarnation of this activity.
mapFragment.setRetainInstance(true);
} else {
// Reincarnated activity. The obtained map is the same map instance in the previous
// activity life cycle. There is no need to reinitialize it.
mMap = mapFragment.getMap();
}
setUpMapIfNeeded();
setUpFieldsIfNeeded();
}
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) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
}
private void setUpFieldsIfNeeded(){
if (fieldsOverlay == null) {
TileProvider tileProvider = new UrlTileProvider(256, 256) {
@Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
//String s = String.format(Locale.US, CMAFieldsRequestFormat, zoom, x, y);
String s = String.format(Locale.US, cartoDBFieldsTile, zoom, x, y);
s =s.replace(" ", "%20");
System.out.println(s);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
fieldsOverlay = mMap.addTileOverlay(
new TileOverlayOptions().tileProvider(tileProvider));
fieldsOverlay.setVisible(false);
fieldsOverlay.setZIndex(1);}
}
TLDR: I'm using google maps with a tileOverlay named fieldsOverlay. When I rotate my device the overlay itself is preserved but it is no longer connected to the variable fieldsOverlay. What is the best way to fix this problem.
Thanks
edit: I was able to get the app to appear to function the way I want by running mMap.clear then reinitializing my layer and setting the visibility to a savedInstanceState value when I reincarnate my activity, but this doesn't seem like a good solution.