【发布时间】:2014-08-12 03:04:31
【问题描述】:
我正在尝试在地图上添加标记,关闭我的应用程序,当打开标记时,标记将位于上次的位置。我正在尝试使用已保存的首选项来执行此操作,但我不完全理解它为什么不保存。
我的代码:
public void onClickMarker(){
b1 = (Button) findViewById(R.id.button1);
b1.setBackgroundResource(R.drawable.parkmycar);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//-----------------------------------------------------------------//
lat = lastLocation.getLatitude();
lng = lastLocation.getLongitude();
SharedPreferences pref = getSharedPreferences("car coordinates",MODE_PRIVATE);
Editor editor = pref.edit();
editor.putLong("lat", Double.doubleToLongBits(lat));
editor.putLong("lng", Double.doubleToLongBits(lng));
editor.commit();
SharedPreferences shared = getSharedPreferences("car coordinates",MODE_PRIVATE);
double myLat = Double.longBitsToDouble(shared.getLong("lat", 0));
double myLng = Double.longBitsToDouble(shared.getLong("lng", 0));
//-----------------------------------------------------------------//
LatLng currLatLng = new LatLng(myLat, myLng);
if(carLoc!=null){
carLoc.remove();
}
carLoc= map.addMarker(new MarkerOptions().position(currLatLng)
.title("your car location")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.unnamed)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currLatLng, 17));
}
});
}
该方法在 onCreate 方法上被调用,并且当它确实将标记放置在当前位置时,但在应用关闭并再次打开后标记将不存在。
【问题讨论】:
-
您是否在应用重启时获得了 lat long 值?
-
不,我在应用重启时没有得到任何值。
-
所以这意味着您的 sharedPreferences 不与 lat long 值一起存储
-
获得纬度和经度值后,将它们存储在 SharedPreferences 中。在应用重新启动时,检查 SharedPreferences 中是否存在任何值 lat 和 long,如果存在,则使用它们来显示标记。
-
@aniruddha 这不是我在代码上所做的吗?
标签: android google-maps sharedpreferences google-maps-api-2