Adding multiple marker locations in Google Maps Android API V2 and save it in Shared Preferences

April 22, 2013

In this article, we will see how to add multiple marker locations in Google Maps Android API V2 and save it in Shared Preferences.

Since the marker locations are stored in Shared Preferences, the markers can be restored on restarting the application.

This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0) and tested in a real Android device (Android 2.3.6  -  GingerBread).

1. Create a new Android application project namely “LocationMarkerPreferences”

Create new Android Application Project

Figure 1 : Create new Android Application Project

2. Configure the project

Configure the application project

Figure 2 : Configure the application project

3. Design application launcher icon

Design application launcher icon

Figure 3 : Design application launcher icon

4. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity

5. Enter MainActivity details

Create a blank activity

Figure 5 : Create a blank activity

6. Download and configure Google Play Services Library in Eclipse

Google Map for Android is now integrated with Google Play Services. So we need to set up Google Play Service Library for developing Google Map application in Android.

Please follow the given below link to setup Google Play Service library in Eclipse.

7. Add Google Play Services Library to this project

Link Google Play Services Library to this project

Figure 6 : Link Google Play Services Library to this project

8. Get the API key for Google Maps Android API V2

We need to get an API key from Google to use Google Maps in Android application.

Please follow the given below link to get the API key for Google Maps Android API v2.

9. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup menu, Click “Android Tools -> Add Support Library “

10. Update the layout file res/layout/activity_main.xml

<RelativeLayout xmlns:android=""
    tools:context=".MainActivity" >

        android:layout_height="match_parent" />


11. Update the class “MainActivity” in the file src/in/wptrafficanalyzer/locationmarkerpreferences/

package in.wptrafficanalyzer.locationmarkerpreferences;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;


public class MainActivity extends FragmentActivity {

    GoogleMap googleMap;
    SharedPreferences sharedPreferences;
    int locationCount = 0;

    protected void onCreate(Bundle savedInstanceState) {

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);

        }else { // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(;

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map

            // Opening the sharedPreferences object
            sharedPreferences = getSharedPreferences("location", 0);

            // Getting number of locations already stored
            locationCount = sharedPreferences.getInt("locationCount", 0);

            // Getting stored zoom level if exists else return 0
            String zoom = sharedPreferences.getString("zoom", "0");

            // If locations are already saved

                String lat = "";
                String lng = "";

                // Iterating through all the locations stored
                for(int i=0;i<locationCount;i++){

                    // Getting the latitude of the i-th location
                    lat = sharedPreferences.getString("lat"+i,"0");

                    // Getting the longitude of the i-th location
                    lng = sharedPreferences.getString("lng"+i,"0");

                    // Drawing marker on the map
                    drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));

                // Moving CameraPosition to last clicked position
                googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));

                // Setting the zoom level in the map on last position  is clicked

        googleMap.setOnMapClickListener(new OnMapClickListener() {

            public void onMapClick(LatLng point) {

                // Drawing marker on the map

                /** Opening the editor object to write data to sharedPreferences */
                SharedPreferences.Editor editor = sharedPreferences.edit();

                // Storing the latitude for the i-th location
                editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(point.latitude));

                // Storing the longitude for the i-th location
                editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(point.longitude));

                // Storing the count of locations or marker count
                editor.putInt("locationCount", locationCount);

                /** Storing the zoom level to the shared preferences */
                editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));

                /** Saving the values stored in the shared preferences */

                Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();


        googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
            public void onMapLongClick(LatLng point) {

                // Removing the marker and circle from the Google Map

                // Opening the editor object to delete data from sharedPreferences
                SharedPreferences.Editor editor = sharedPreferences.edit();

                // Clearing the editor

                // Committing the changes

                // Setting locationCount to zero


    private void drawMarker(LatLng point){
        // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();

        // Setting latitude and longitude for the marker

        // Adding marker on the Google Map

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

12. Update the file AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="17" />


    <uses-permission android:name="in.wptrafficanalyzer.locationmarkerpreferences.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name=""/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

            android:value="YOUR_ANDROID_API_KEY" />


13. Executing the application

In Eclipse IDE, we can execute the application from the menu “Run -> Run as -> Android Application”.

The Android application in action

Figure 7 : The Android application in action

14. Download the source code

How to hire me?

I am George Mathew, working as software architect and Android app developer at

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to

My other blogs

Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :

Tags: , , , , , , , ,

20 Responses to Adding multiple marker locations in Google Maps Android API V2 and save it in Shared Preferences

  1. Basribaz on April 23, 2013 at 7:43 am

    how to add data maps using google maps as the location of a particular area with the help of php and mysql as the following example:

    if (position == 0) { Intent intent = new Intent (Intent.ACTION_VIEW, Uri.parse (“,120.042854″)); intent.setComponent (new ComponentName (“”, “”)); startActivity (intent);

    the data is displayed with listview

    thanks for the help

  2. Sultan Ishmuradov on April 30, 2013 at 9:49 pm

    can you help me to add multiple proximity alerts plz its too important for me

  3. Brook on May 31, 2013 at 12:22 pm

    Why my locationCount is 0?

  4. Prasad on July 25, 2013 at 12:49 pm

    Hi George,
    Can you help me to draw a route lines between multiple markers.I used Polyline but it didn’t display the correct result.When we zoom on map then that inbetween markers are not displayed on that line.
    Awaiting for your reply.

  5. Vinicius on August 1, 2013 at 8:05 am

    exactly what I needed thank you

  6. Lapetole on October 12, 2013 at 2:40 pm

    Hi thanks for these very usefull examples.
    Do you have one adding markers parsing an xml online file?
    Thanks for answering or telling if u know a tutorial on this subject.

  7. Aleksandar on September 4, 2014 at 1:31 am

    Is it possible to import exiting markers from my custom map from in to google maps api v2 for androids? Because when i put application on market i wont update every single time when i put few more markers on map.. so is it possible for me to import markers from web?

  8. Jopecayo on November 10, 2014 at 6:47 pm

    Is it possible to find location through user’s input of latitude and longitude?

  9. Hermanni Gert on December 20, 2014 at 10:18 pm

    Hallo und Danke für Ihre super Tollen Bespiele, ich bin dabei Android zu lernen und möchte in eine Google Karte mehrere Marker mit einer xml Datei laden. Ich bekomme es aber nicht hin, nur wenn ich die Marker in Programmcode schreibe. Aber ich möchte die Marker von Zeit zu Zeit ändern. Ich habe mir eine andere App geschrieben mit Mietern die ich austauschen kann wie ich möchte, das funktionier super, aber wenn ich auf den gleichen Weg die lat und lng daten einlesen möchte kommt der Fehler: The method addMarker(MarkerOptions) is undefined for the type HashMap ??? Haben Sie vielleicht ein Bespiel Script das mir weiter hilft? Das wäre super.
    Mit freundlichen Grüßen

  10. Midhun Ek on December 25, 2014 at 12:43 pm

    Sir….Wonderful Tutorial was it
    Please Help me to add lat long manually on the map…

  11. krishna on February 10, 2015 at 12:01 pm

    how can i access only 10km range marker from current location

  12. Pulkit on March 28, 2015 at 1:48 pm

    Awesome tutorial !!! <3

  13. saurabh bhat on July 31, 2015 at 3:13 pm

    How do i load the markers based on my current location from server can you please help

  14. Melwin on October 6, 2015 at 5:10 pm

    Hi George,

    It was great that your program could do what i wanted I am really Impressed,
    I was developing a project in which I should have custom markers from database. In which i’ll save the address and take lat and long like there might be 4 to 5 of them and save it in database and how to show them in the map. and convert address to lat and long.. Please do help…

  15. Amsaraj on December 11, 2015 at 1:39 pm

    Hi George Mathew,

    I’m looking for a way to add Markers to a StreetViewPanorama using the Google Maps SDK for Android.i cannot find any documentation or sample code that does this on is possible. please guide me Thanks in advance.
    sorry for this question.this question not related on our post.but i struggling many days this issue.

  16. jayshree sonawane on March 26, 2016 at 10:04 pm

    Hi sir ,

    sir how to remove multiple marker in map .In my project some address showing multiple marker i want only one marker in map for that specific address.
    sir please help me ….

  17. Jing Huang on May 26, 2016 at 4:08 am

    Hi Thank you so much George for nice posting. I have multiple pair of zipcode and latitude/longitude stored in SQLite Database and I would like to map them on to Google map. It seems to me that your example utilize existing stored the data in location. Could you provide me some hint to me to solve my problem?

    many many thanks

  18. Kabir on June 10, 2016 at 1:33 pm

    hi sir,
    i want to get the multiple addresses from listview and show in map . i already have addresses in listview.

Leave a Reply to Jing Huang Cancel reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner