Android API Google Maps v2 - Map State Recovery

I am creating a very simple map application using the Google Maps Android API v2. As expected, when the user leaves and then returns to the application, any changes that they made in location, scaling, etc., are lost as the activity is destroyed and recreated.

I know that I can save the state of the map camera programmatically (possibly as the values ​​in the general settings) in onPause() and restore it to onResume() , but does the API have any built-in mechanism for saving the state of the map between the start of activity

+4
source share
2 answers

I don't think you can, but you can save your CameraPosition , which has your position / scale / angle ...

http://developer.android.com/reference/com/google/android/gms/maps/model/CameraPosition.html

so that you can write a function in onDestroy that receives a CameraPosition from your map and stores it in SharedPreferences . In onCreate() you recreate your CameraPosition from SharedPreferences (after your map has been created).

 // somewhere in your onDestroy() @Override protected void onDestroy() { CameraPosition mMyCam = MyMap.getCameraPosition(); double longitude = mMyCam.target.longitude; (...) SharedPreferences settings = getSharedPreferences("SOME_NAME", 0); SharedPreferences.Editor editor = settings.edit(); editor.putDouble("longitude", longitude); (...) //put all other values like latitude, angle, zoom... editor.commit(); } 

in onCreate()

 SharedPreferences settings = getSharedPreferences("SOME_NAME", 0); // "initial longitude" is only used on first startup double longitude = settings.getDouble("longitude", "initial_longitude"); (...) //add the other values LatLng startPosition = new LatLng() //with longitude and latitude CameraPosition cameraPosition = new CameraPosition.Builder() .target(startPosition) // Sets the center of the map to Mountain View .zoom(17) // Sets the zoom .bearing(90) // Sets the orientation of the camera to east .tilt(30) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder 

create a new camera and configure it. make sure the card is installed at this point

  map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 
+9
source

In this case, there is no use of the API.

You can try this library: https://github.com/fsilvestremorais/android-complex-preferences

It will not be as efficient as just writing a bunch of SharedPreferences.Editor.put... for values ​​from CameraPosition to onPause because it uses Gson inside, but it saves some time if you have a more complex object to save and restore.

In any case, you can also send a function request to gmaps-api-issues (or Android map extensions ). Of course, something is missing to easily stand simple objects ( CameraPosition , LatLng , LatLngBounds ).

0
source

Source: https://habr.com/ru/post/1482217/


All Articles