Draw lines on Google Maps Android API

Last modified on August 1st, 2014 by Joe.

This Android tutorial will help a beginner to start with Google Maps on an Android device. We will be using Google Maps Android API V2 and it is an introductory level tutorial. We will show some chosen locations in Google map using Latitude and Longitude and draw lines (polyline) between them. This is continuation of the earlier written tutorial to show a map using Google Maps Android API.

Android Map

The android map we will get using the Google Maps (V2) API is same as what we get in Google’s maps app for mobile (GMM). We can construct a Google map object using GoogleMap class. To display the constructed Google map in the Android Ui, we can use MapFragment or MapView object. We should use SupportMapFragment for devices running older versions of Android. I am using a HTC Android mobile running Android Version 2.3.5.

Prerequisite for using Google Maps API

  1. In Google Console Create Project: Go to https://cloud.google.com/console/project and create a project go into it.
  2. Enable Google Maps Android API v2: Go to menu “APIs & auth –> APIs” and switch on.

    Enable-Google-Maps-Android-API-v2

  3. Create SHA1 Android Key: Run the following in cmd prompt.
    keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android 

    Sha1-Android-Key

  4. Create Google Android API Key: Go to Menu “Credentials” and under the section Public API access, click Create New Key. There are different types of keys and we should create“Android Key”. In the textarea give input the SHA1 certificate fingerprint and package of the andoird app separated by a semicolon as shown below,Google-Android-API-Key

  5. Google Play Services in SDK: is required for Google Maps Android API. Check the Android SDK Manager and its in the bottom under Extras group,

    Android Google Play Services

  6. Google APIs: “Google APIs” should be installed. Check under the Android API version for Google API.

    Google APIs

  7. Google-Play-Services_Lib project as dependency: Import Google play services lib project into workspace (if you use Android Studio skip this step). In Eclipse, Click File > Import, select Android > Existing Android Code into Workspace. This project should be available as part of the android-sdk download. After importing we need to add this project as dependency to the Android application we are going to create.

    Import Google Lib

    google-play-services-android-dependency

Show Map in Activity

MapFragment / SupportMapFragment acts as a wrapper around the GoogleMap object and it extends Fragment class. In an Android activity, a map can be added directly using the following XML code snippet,

activity_main.xml

<LinearLayout 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"
          android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

MainActivity.java

Android activity part is key and simple. All the job will be taken care by Google Maps Android API and all we have to do is just a simple call and embed the maps in the activity using the fragment. For this example Android app I have chosen three places in Manhattan, Newyork. Using their latitude and longitude I have zoomed in on that location and have drawn polyline between those places. Its just a straight line and does not follow any road route.

package com.javapapers.android;

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

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity {
	private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,
			-73.998585);
	private static final LatLng TIMES_SQUARE = new LatLng(40.7577, -73.9857);
	private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);

	private GoogleMap googleMap;

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

	private void setUpMapIfNeeded() {
		// check if we have got the googleMap already
		if (googleMap == null) {
			googleMap = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();
			if (googleMap != null) {
				addLines();
			}
		}
	}

	private void addLines() {

		googleMap
				.addPolyline((new PolylineOptions())
						.add(TIMES_SQUARE, BROOKLYN_BRIDGE, LOWER_MANHATTAN,
								TIMES_SQUARE).width(5).color(Color.BLUE)
						.geodesic(true));
		// move camera to zoom on map
		googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LOWER_MANHATTAN,
				13));
	}
}

AndroidManifest.xml

In Android manifest file we need to enable permission for using google maps, internet and etc. Most importantly the Android API key created using Google console should be given here as meta-data inside the application tag. Remember to use the same package which you have used to create the Android api key.

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

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

    <permission
        android:name="com.javapapers.android.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.javapapers.android.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <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="com.javapapers.android.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.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzbSyB2dHv8DAesjxXTAxW9olS9pew9YWECqSU" />
    </application>

</manifest>

Map showing Lines Drawn using Google Maps Android API

2014-02-17_19-14-39

Download Example Android Application

Comments on "Draw lines on Google Maps Android API"

  1. […] the previous Android tutorial on how to draw lines on map using Google Maps Android API for basics on Google maps and prerequisite. Now lets directly jump to the tutorial on adding […]

  2. […] This tutorial is a part of Google maps series. I recommend you to go through the previous tutorial Draw lines on Google Maps Android API. This earlier tutorial is to draw straight lines (polyline) between given latitude and […]

  3. RAnjeet says:

    only white space is coming nothing else showing to me ….

Comments are closed for "Draw lines on Google Maps Android API".