user3449550
user3449550

Reputation: 123

How to save a marker onMapClick?

Hi I have this code which adds a marker when I click on the map but if i rerun the app the marker disappears. Is there any way that I can store the marker somehow and then display it ? I have read about shared preferences but I can't provide the code for it. How can I save the onmapclick action in shared preferences and then display it ?Anyone can help me out ?

 gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener(){

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

    }

});

Upvotes: 0

Views: 5274

Answers (1)

Talha Q
Talha Q

Reputation: 4360

Check this link if you still need any help.

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();

}

}); 

To remove marker

gMap.setOnMarkerClickListener(new OnMarkerClickListener() {

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

How to create custom marker with your own image

// 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);

Upvotes: 2

Related Questions