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

April 22, 2013
By

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.

http://developer.android.com/google/play-services/setup.html


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.

https://developers.google.com/maps/documentation/android/start


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="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


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


package in.wptrafficanalyzer.locationmarkerpreferences;

import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap googleMap;
    SharedPreferences sharedPreferences;
    int locationCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 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);
            dialog.show();

        }else { // Google Play Services are available

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

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

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // 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
            if(locationCount!=0){

                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.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
            }
        }

        googleMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {
                locationCount++;

                // Drawing marker on the map
                drawMarker(point);

                /** 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 */
                editor.commit();

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

            }
        });

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

                // Removing the marker and circle from the Google Map
                googleMap.clear();

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

                // Clearing the editor
                editor.clear();

                // Committing the changes
                editor.commit();

                // Setting locationCount to zero
                locationCount=0;

            }
        });
    }

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

        // Setting latitude and longitude for the marker
        markerOptions.position(point);

        // Adding marker on the Google Map
        googleMap.addMarker(markerOptions);
    }

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


12. Update the file AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationmarkerpreferences"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <permission
        android:name="in.wptrafficanalyzer.locationmarkerpreferences.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <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="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.locationmarkerpreferences.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR_ANDROID_API_KEY" />

    </application>
</manifest>


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 wptrafficanalyzer.in

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

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


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 (“http://maps.google.com/maps?f=d&daddr=-4.140517,120.042854″)); intent.setComponent (new ComponentName (“com.google.android.apps.maps”, “com.google.android.maps.MapsActivity”)); 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
    thanks

  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 maps.google.com 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
    Gert

  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 Android.it 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

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner