标记在重新运行应用程序后消失

时间:2014-02-26 12:54:29

标签: android google-maps google-maps-markers markers

您好我在谷歌地图上工作,我正在尝试创建一些onMapClick听众,所以当用户点击地图时会创建一个标记。一切都很好,但当我关闭并重新运行应用程序时,标记不存在。有没有办法让标记保持不变?有什么建议吗?非常感谢。

这是我的代码,其中在onmapclick事件上创建标记。标记位置美国被创建并且它始终存在于特定的latlng但是当我点击地图时,为什么当重新编译并且标记LOCATION_AMERICA仍然存在时,地图上添加的标记消失。请帮忙

             protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gMap=   
               ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
    gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    gMap.addMarker(new MarkerOptions()
    .position(LOCATION_AMERICA).
    title("AMERICA").
    snippet("Population:5.000.0000"));
    gMap.setMyLocationEnabled(true);
    configureImageButton();

             gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng position) {



            gMap.addMarker(new MarkerOptions().position(position)
                    .title("HOTEL")
                    .snippet("RESTAURANT")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

        }
    });}

1 个答案:

答案 0 :(得分:0)

您可以使用Shared Preferences,这样每次添加标记时,都会将其LatLng保存在共享首选项中。关闭应用程序并再次打开它后,您将加载共享首选项并获取所有已保存的LatLng,您将能够再次绘制标记。

      SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
//here you can load the number of markers you have
            //appSharedPrefs.getInt("MarkersCount", 0);
//then you will load the markers lat and lng by incremented id and draw the markers

// when you draw a new marker in the onMapClickListener
 gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng position) {



                gMap.addMarker(new MarkerOptions().position(position)
                        .title("HOTEL")
                        .snippet("RESTAURANT")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
    // Here you will have to save lat lng in string and save it in the shared preferences with incremented id
//  then add the number of markers in the sharedPreferences.
            }
        });
相关问题