Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save markers on Android google maps v2

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()));
like image 831
CrashOverride Avatar asked Jan 24 '13 04:01

CrashOverride


People also ask

How do I add a marker to Google Maps Android?

For adding a custom marker to Google Maps navigate to the app > res > drawable > Right-Click on it > New > Vector Assets and select the icon which we have to show on your Map. You can change the color according to our requirements. After creating this icon now we will move towards adding this marker to our Map.

Can you drop markers on Google Maps?

To drop a pin on Google Maps when using an Android device: Open the Google Maps app. Either search for an address or scroll around the map until you find the location you want. Long-press on the screen to drop a pin.


1 Answers

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();
}
like image 111
CrashOverride Avatar answered Sep 22 '22 01:09

CrashOverride