Google Maps Android API v2-恢复地图状态 [英] Google Maps Android API v2 - restoring map state
问题描述
我正在使用Google Maps Android API v2构建一个非常简单的地图应用.正如预期的那样,当用户离开并返回到应用程序时,由于活动被销毁并重新创建,他们在位置,缩放等方面所做的任何更改都会丢失.
I'm building a very simple map app using Google Maps Android API v2. As expected, when the user leaves and then returns to the app, any changes they've made in location, zoom, etc. are lost as the activity is destroyed and re-created.
我知道我可以在onPause()
中以编程方式保存地图的相机状态(也许作为共享首选项中的值),并在onResume()
中将其还原,但是API是否具有任何内置机制来在活动启动之间持久保存地图状态?
I know I can save the map's camera state programmatically (perhaps as values in shared preferences) in onPause()
and restore it in onResume()
, but does the API have any built-in mechanism for persisting map state between activity launches?
推荐答案
我认为您不能,但是您可以保存具有位置/缩放/角度...的CameraPosition
.
I don't think you can, but you can save your CameraPosition
which has your Position/Zoom/Angle...
http://developer.android. com/reference/com/google/android/gms/maps/model/CameraPosition.html
,因此您可以在onDestroy
中编写一个从地图中获取CameraPosition
并将其存储在SharedPreferences
中的函数.在onCreate()
中,您从SharedPreferences
重新创建CameraPosition
(在实例化地图之后).
so you can write a function in your onDestroy
which gets the CameraPosition
from your map and store it in your SharedPreferences
. In your onCreate()
you recreate your CameraPosition
from the SharedPreferences
(after your map is instanciated).
// 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();
}
在您的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
创建一个新的cameraPosition并对其进行动画处理.可以肯定的是,此时地图已经实例化
create a new cameraPosition and animate it. be sure, map is instanziated at that point
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
这篇关于Google Maps Android API v2-恢复地图状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!