Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Check this link if you still need any help.

Markerm=null;
SharedPreferencesprefs=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 valuesif((prefs.contains("Lat")) && (prefs.contains("Lng"))
{   
Stringlat= prefs.getString("Lat","");
Stringlng= prefs.getString("Lng","");    
LatLngl=newLatLng(Double.parseDouble(lat),Double.parseDouble(lng));
gMap.addMarker(newMarkerOptions().position(l));

}

Inside your onMapClick

gMap.setOnMapClickListener(newGoogleMap.OnMapClickListener(){   
@OverridepublicvoidonMapClick(LatLng point) {
   marker = gMap.addMarker(newMarkerOptions().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(newOnMarkerClickListener() {

@OverridepublicbooleanonMarkerClick(Marker arg0) {
//Your marker removed    
marker.remove();
returntrue;
}
});

How to create custom marker with your own image

// create markerMarkerOptionsmarker=newMarkerOptions().position(newLatLng(lat, lng);

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

// adding marker
gMap.addMarker(marker);

Post a Comment for "How To Save A Marker Onmapclick?"