Drawing Polyline and Markers along the tapped positions in Google Map Android API V2 using ArrayList

March 4, 2013
By

In this article, we will create an Android application which draws polyline and markers along the tapped positions in Google Map Android API V2. Long click the Google Map to clear all the existing polylines and markers in the Google Map.

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


1. 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

Note : Please ensure that, the latest version of Google Play Service Library is installed


2. Create a new Android Application Project namely “LocationPolyline”

Create new Android Application Project

Figure 1 : Create new Android Application Project


3. Configure Android Application Project

Configure Android application project

Figure 2 : Configure Android application project


4. Design Application Launcher Icon

Design application launcher icon

Figure 3 : Design application launcher icon


5. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


6. Enter Main Activity Details

Enter MainActivity details

Figure 5 : Enter MainActivity details


7. Link to Google Play Services Library

Link to Google Play Services library

Figure 6 : Link to Google Play Services library


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 window, 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"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>


11. Update the file src/in/wptrafficanalyzer/locationmarkerlatlng/MainActivity.java


package in.wptrafficanalyzer.locationpolyline;

import java.util.ArrayList;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

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;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap googleMap;
    ArrayList<LatLng> points;

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

        points = new ArrayList<LatLng>();

        // 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);

        // Setting OnClick event listener for the Google Map
        googleMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Instantiating the class MarkerOptions to plot marker on the map
                MarkerOptions markerOptions = new MarkerOptions();

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

                // Setting titile of the infowindow of the marker
                markerOptions.title("Position");

                // Setting the content of the infowindow of the marker
                markerOptions.snippet("Latitude:"+point.latitude+","+"Longitude:"+point.longitude);

                // Instantiating the class PolylineOptions to plot polyline in the map
                PolylineOptions polylineOptions = new PolylineOptions();

                // Setting the color of the polyline
                polylineOptions.color(Color.RED);

                // Setting the width of the polyline
                polylineOptions.width(3);

                // Adding the taped point to the ArrayList
                points.add(point);

                // Setting points of polyline
                polylineOptions.addAll(points);

                // Adding the polyline to the map
                googleMap.addPolyline(polylineOptions);

                // Adding the marker to the map
                googleMap.addMarker(markerOptions);

            }
        });

        googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng point) {
                // Clearing the markers and polylines in the google map
                googleMap.clear();

                // Empty the array list
                points.clear();
            }
        });
    }

    @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.locationpolyline"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

    <uses-permission android:name="in.wptrafficanalyzer.locationpolyline.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.locationpolyline.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_API_KEY"/>

    </application>
</manifest>

Note : Replace “YOUR_API_KEY” at line 44 with the api key obtained in step 8.


13. Screenshot of the application

Application in execution

Figure 7 : Application in execution


14. Download 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: , , , , , , ,

5 Responses to Drawing Polyline and Markers along the tapped positions in Google Map Android API V2 using ArrayList

  1. Jin on September 4, 2014 at 10:29 am

    Hiļ¼Œsir:
    I want to know, how to make Google’s position is not displayed, it is one second while brushing time positioning data

  2. evy on November 30, 2014 at 5:18 pm

    Hi, sir. how to making polyline with start button, and stop making polyline with stop button in android? can you help me?

  3. Laura on January 28, 2015 at 8:45 pm

    Hi sir, I want to know if it is posible to change the polyline style, but that I mean instead of draw line draw a bitmap

  4. Ajeet Bishnoi on July 7, 2015 at 7:44 pm

    thanks for
    plz sir send code of Polyline save in SharedPreferences

  5. Param on January 19, 2016 at 12:32 pm

    hello sir i have list of latitute and longitute with name and image in json array. now i want to show them on google map please help me

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