Save markers on Android google maps v2
Asked Answered
D

3

6

I am using Android Google maps v2 API and have it set up to add markers on long click. I need a way to save these markers and reload them when the app resumes again. What will be the best way to do this? Please help

Currently I add markers as follows:

map.addMarker(new MarkerOptions().position(latlonpoint)
            .icon(bitmapDescriptor).title(latlonpoint.toString()));
Dermatitis answered 24/1, 2013 at 4:42 Comment(4)
I want to save the markers. I suppose saving just marker location (lat/long values) somewhere (I don't know where and how).Dermatitis
I see..What you want is,after setting the marker in A screen, you(or users) leave A screen and go B screen, And then when you come back to A screen again from B screen, you want to see the state of A screen as what it was. Right??Lynxeyed
Yes. Thats exactly correct. And not just different screens of the app. But also when the app exits and you revisit the app like the next day. I should be able to get back the old markers. I actually found a solution which I posted myself down below. But if you have a better solution, I am all ears!Dermatitis
aha, now I can understand what you said: NOT resume, BUT "restart" your app at any time after your app destroyed entirely. In that case, what you wrote below looks like correct. For more, see this HOW TO SAVE data.Lynxeyed
D
6

I got it! I can easily do this via saving the array list of points to a file and then reading them back from file

I do the following onPause:

try {
    // Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
    FileOutputStream output = openFileOutput("latlngpoints.txt",
    Context.MODE_PRIVATE);
    DataOutputStream dout = new DataOutputStream(output);
    dout.writeInt(listOfPoints.size()); // Save line count
    for (LatLng point : listOfPoints) {
        dout.writeUTF(point.latitude + "," + point.longitude);
        Log.v("write", point.latitude + "," + point.longitude);
    }
    dout.flush(); // Flush stream ...
    dout.close(); // ... and close.
} catch (IOException exc) {
    exc.printStackTrace();
}

And onResume: I do the opposite

try {
    FileInputStream input = openFileInput("latlngpoints.txt");
    DataInputStream din = new DataInputStream(input);
    int sz = din.readInt(); // Read line count
    for (int i = 0; i < sz; i++) {
        String str = din.readUTF();
        Log.v("read", str);
        String[] stringArray = str.split(",");
        double latitude = Double.parseDouble(stringArray[0]);
        double longitude = Double.parseDouble(stringArray[1]);
        listOfPoints.add(new LatLng(latitude, longitude));
    }
    din.close();
    loadMarkers(listOfPoints);
} catch (IOException exc) {
    exc.printStackTrace();
}
Dermatitis answered 24/1, 2013 at 22:24 Comment(12)
I think your code is a good trial, but I think you'd better use the the lifecylce of the Activity, which is very simple way according to the Android Development Guide. Consider using the Activity lifecycle after reading this Android Development Guide:click here. I think that is what you want to do,Lynxeyed
I looked into that a little but onSaveInstanceState seems like a temporary fix. It wont store the data more permanently.Dermatitis
aha, now I can understand what you said: NOT resume, BUT "restart" your app at any time after your app destroyed entirely. In that case, what you wrote above looks like correct. For more, see this HOW TO SAVE data.Lynxeyed
Yea thats what I meant. Sorry for the confusion!Dermatitis
@Dermatitis just a quick question? At listOfPoints i get an error saying listOfPoints cannot be resolved and then at for (LatLng point : listOfPoints) { (under listOfPoints i get listOfPoints cannot be resolved to a variable Could you please help? I want to able to save my markers as well and have been struggling for the last week! Please helpHawken
You will need to create a list called "listOfPoints" which has LatLng type of objects stored.Dermatitis
@Dermatitis would you be kind enough to show me how to do this?Hawken
You may initialize like this List<LatLng> listOfPoints = new ArrayList<LatLng>();Dermatitis
@Dermatitis thanks, but unfortunately it doesn't save my markers added, i think it might be because in my app i add the markers differently to yours. But thanks for your help though! If you want to you, would you be able to assist if i give you my code?Hawken
@Dermatitis Hi, did you have to create any new text files for this? And could you also post the loadMarkers method please?Espy
@lincolnWhite I did not have to create any new text files. The code takes care of creating text files. I no longer have access to the code base... this was a older project I worked on. But I believe loadMarkers should iterate through the list of markers and add the markers to the map as follows map.addMarker(new MarkerOptions().position(latlonpoint) .icon(bitmapDescriptor).title(latlonpoint.toString()));Dermatitis
This was so much better for me than SharedPreferences or a database. Nice code, man.Pilcomayo
E
0

You can implement the onLongClickListener for the marker as below :

map.addMarker(new MarkerOptions()
    .position(latlonpoint)
    .icon(bitmapDescriptor)
    .title(latlonpoint.toString()));
map.setOnMapLongClickListener(new OnMapLongClickListener() {
    @Override
    public void onMapLongClick(LatLng p_point) {
        // TODO ...
    }
});
Euterpe answered 24/1, 2013 at 4:57 Comment(4)
I don't think you understood the question properly. I need a way to save and reload the markers that I add. That is when one exits the app it should save all the current markers and reload them once the app resumes again. How does implementing onLongClickListener help with this?Dermatitis
@CrashOverride...Grishu's answer above is to let you know HOW TO use the correct writing code of the ClickListener. His answer is the basic formular we have to know in order to apply onClickListener to the code. That's it all, I think.Lynxeyed
@BBonDoo- I am totally agree with you. You are right. Thanks a lot . I have only provided the solution for the onLongClickListener only.Euterpe
Yes I understand this is a code to implement onLongClickListener. Thank you for it but that is not what I need or asked for. Anyways I don't want to dwell off topic too much. But again, thanks!Dermatitis
T
0

First save latitude and longitude on long click in the database

Note:-ignore place no need for that

 HistoryModel historyModel = new HistoryModel(place,sLatitude, sLongitude);
 DatabaseMethods.openDB(MapsActivity.this);
 DatabaseMethods.addHistory(historyModel);
 DatabaseMethods.closeDB();

In onMapReady callback

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    DatabaseFunctions.openDB(MapsActivity.this);
    ArrayList<HistoryModel> historyModelArr = DatabaseFunctions.getHistory();
    DatabaseFunctions.closeDB();

    for (int i = 0; i < historyModelArr.size(); i++) {
        double latitude = Double.parseDouble(historyModelArr.get(i).getLatitude());
        double longitude = Double.parseDouble(historyModelArr.get(i).getLongitude());
        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude)));
    }
}

Used Methods :-

   public static ArrayList<HistoryModel> getHistory() {
    Cursor cursor = null;
    ArrayList<HistoryModel> historyModelArr = null;
    try {
        cursor = db.rawQuery("SELECT * FROM " + DBHelper.TABLE_HISTORY,
                null);

        if (cursor != null) {
            historyModelArr = new ArrayList<HistoryModel>();
            while (cursor.moveToNext()) {
                HistoryModel historyModel = new HistoryModel(cursor.getString(1),cursor.getString(2), cursor.getString(3));
                historyModelArr.add(historyModel);
            }
            return historyModelArr;
        } else {
            return historyModelArr;
        }

    } catch (Exception e) {
        Log.e(tag, "getHistory Error : " + e.toString());
        return historyModelArr;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}



public static void addHistory(HistoryModel historyModel) {

    ContentValues values;
    try {
        values = new ContentValues();
        values.put(DBHelper.HISTORY_PLACE, historyModel.getPlace());
        values.put(DBHelper.HISTORY_LATITUDE, historyModel.getLatitude());
        values.put(DBHelper.HISTORY_LONGITUDE, historyModel.getLongitude());
        db.insert(DBHelper.TABLE_HISTORY, null, values);
    } catch (Exception e) {
       
    }

}

Model Class

public class HistoryModel {

private String place, latitude, longitude;

public HistoryModel(String place, String latitude, String longitude) {
    this.place = place;
    this.latitude = latitude;
    this.longitude = longitude;
}


public String getPlace() {
    return place;
}

public void setPlace(String place) {
    this.place = place;
}

public String getLatitude() {
    return latitude;
}

public void setLatitude(String latitude) {
    this.latitude = latitude;
}

public String getLongitude() {
    return longitude;
}

public void setLongitude(String longitude) {
    this.longitude = longitude;
}
}
Thalweg answered 1/10, 2021 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.