如何在MapClick上保存标记?

时间:2014-04-02 14:22:28

标签: android sharedpreferences google-maps-markers

嗨我有这个代码,当我点击地图时会添加一个标记,但如果我重新运行应用程序,标记就会消失。有什么方法可以以某种方式存储标记,然后显示它?我已经阅读了有关共享首选项的内容,但我无法为其提供代码。如何在共享首选项中保存onmapclick操作然后显示?任何人都可以帮助我吗?

 gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener(){

    @Override
    public void onMapClick(LatLng point) {
        gMap.addMarker(new MarkerOptions().position(point));

    }

});

1 个答案:

答案 0 :(得分:2)

如果您仍需要任何帮助,请查看此link

Marker m = null;
SharedPreferences prefs = null;//Place it before onCreate you can access its values any where in this class

// onCreate method started 

prefs = this.getSharedPreferences("LatLng",MODE_PRIVATE); 
//Check whether your preferences contains any values then we get those values
if((prefs.contains("Lat")) && (prefs.contains("Lng"))
{   
String lat = prefs.getString("Lat","");
String lng = prefs.getString("Lng","");    
LatLng l =new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
gMap.addMarker(new MarkerOptions().position(l));

}

Inside your onMapClick

gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener(){   
@Override
public void onMapClick(LatLng point) {
   marker = gMap.addMarker(new MarkerOptions().position(point));

/* This code will save your location coordinates in SharedPrefrence when you click on the map and later you use it  */
prefs.edit().putString("Lat",String.valueOf(point.latitude)).commit();
prefs.edit().putString("Lng",String.valueOf(point.longitude)).commit();

}

}); 

删除标记

gMap.setOnMarkerClickListener(new OnMarkerClickListener() {

@Override
public boolean onMarkerClick(Marker arg0) {
//Your marker removed    
marker.remove();
return true;
}
});

如何使用您自己的图片创建自定义标记

// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lng);

// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.your_own_image)));

// adding marker
gMap.addMarker(marker);