Save Google Maps to SharedPreferences
source link: https://www.codesd.com/item/save-google-maps-to-sharedpreferences.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Save Google Maps to SharedPreferences
I'm trying to store my GMaps markers, so when I press back button, and back another time to my maps activity, show my markers on screen.
I've checked out this post Save state when back button is pressed and I got some results, but I'm still far way from my initial objective.
Now I can see my first marker and my last one.
Here goes my code:
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private List<Marker> markerList;
public MapsActivity(){
if(markerList == null){
markerList = new ArrayList<Marker>();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
LoadPreferences();
Intent intent = getIntent();
Bundle data = intent.getExtras();
String label = data.getString("sum");
int newLatitude = data.getInt("firstNumber");
int newLongitude = data.getInt("secondNumber");
MarkerOptions mo = new MarkerOptions().position(new LatLng(newLatitude, newLongitude)).title(label);
markerList.add(mMap.addMarker(mo));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
@Override
public void onBackPressed(){
super.onBackPressed();
SavePreferences();
}
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("listSize", markerList.size());
for(int i = 0; i <markerList.size(); i++){
editor.putFloat("lat"+i, (float) markerList.get(0).getPosition().latitude);
editor.putFloat("long"+i, (float) markerList.get(0).getPosition().longitude);
editor.putString("title"+i, markerList.get(0).getTitle());
}
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
int size = sharedPreferences.getInt("listSize", 0);
for(int i = 0; i < size; i++){
double lat = (double) sharedPreferences.getFloat("lat"+i,0);
double longit = (double) sharedPreferences.getFloat("long"+i,0);
String title = sharedPreferences.getString("title"+i,"NULL");
markerList.add(mMap.addMarker(new MarkerOptions().position(new LatLng(lat, longit)).title(title)));
}
}
}
My question is how can I store my markers that when I back to maps activity show them? (Using this or another approach)
problem:
markerList.get(0)
You are only saving the first index of your array of markers
solution:
feed the index from the foorloop
markerList.get(i)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK