Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save added google maps overlays in an android app?

I created an app in which users can add various markers on google maps using overlays. I want the app to save the overlay when the user creates it so that when they re-open the app later the markers will still be present.
Currently anytime the app is re-opened the created markers are gone. I have searched the internet and have not gotten a clear understanding of how to save my markers/overlays offline for later use.

like image 873
Lance Avatar asked Sep 26 '11 00:09

Lance


2 Answers

As mentioned, you need to use some persistent storage. Perhaps, database would be an excess in your particular case (if you simply need to save a bunch of longitude-latitude pairs), and Shared Preferences would fit your needs. If you rarely need to read/store this data, then putting JSONArray as a String to Shared Preferences would be the simplest (in terms of reading and extracting data) solution:

    SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
    JSONArray jsonArr = new JSONArray();
    JSONObject json;
    for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
        json = new JSONObject();
        json.put("lat", user_markers.get(i).getLat());
        json.put("long", user_markers.get(i).getLong());
        jsonArr.put(json);
    }
    editor.putString("markers", jsonArr.toString());
    editor.commit();

If you need to read/store this data a bit more often, then you may assign ids/indexes to separate SharedPreferences's values, but this may require more complicated extraction method. For example:

    SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
    int id;
    for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
        id = user_markers.get(i).getId(); // some Id here
        // or simply id = i;
        editor.putString("markers_lat_" + id, user_markers.get(i).getLat());
        editor.putString("markers_long_" + id, user_markers.get(i).getLong());
    }
    editor.commit();

After all, you should consider using database if you plan to store big amount of data or data of complicated structure.

like image 157
a.ch. Avatar answered Sep 30 '22 12:09

a.ch.


It just an idea, but you can save your markers in database and when you reopen your map just query database and put it on the map again...

like image 27
Jovan Avatar answered Sep 30 '22 13:09

Jovan