Home > Draw Route from Source to Destination on Google Map

Draw Route from Source to Destination on Google Map

This tutorial explain how to Draw route from Source to Destination on Google Map in android application.

1. Setup on Goggle Developer Console

1. Go to Goggle Developer Console https://console.developers.google.com/

After successfull login go to the console you can start by creating your New project. I choose project name "PlaceApi"

2. After successfully created project select project

3. After created project Enable Google Place API for Android

Click on Google Place API for Android for enable api

Click on Enable button

4. Go to Credentials left hand side menu and create API Key

Press on create credential blue button & select API Key after that API key created dialog show press close button in this dialog.

After successfully copy key & save on note pad these key use in android application.


2. Creating Android Project

1. Create a new project in Android Studio from File ? New Project and fill the project details.


2. Open build.gradle add Google Play Services 'com.google.android.gms:play-services:8.4.0' after adding click on Sync Now

									
apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.androidlearningtutorials.route" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" multiDexEnabled true } android { packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:25.2.0' compile 'com.google.android.gms:play-services:8.4.0' }

3. Add the below permissions to AndroidManifest.xml file.

									
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidlearningtutorials.route"> <!-- need permission for google map --> <permission android:name="com.androidlearningtutorials.route.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-library android:name="com.google.android.maps" /> <uses-permission android:name="com.androidlearningtutorials.route.permission.MAPS_RECEIVE" /> <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" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <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" /> <!-- paste created google API Key --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyAuzgqhQwVOse91QJLf2MI58xE9-gKTwV8"/> </application> </manifest>

4. Now open activity_main.xml modified like as below.

									
<?xml version="1.0" encoding="utf-8"?> <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" android:background="#ffb2b2b2" android:orientation="vertical" android:padding="10dip"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Google Place API Demo" android:textSize="18dip" android:textColor="#000000" android:layout_gravity="center_horizontal"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="bottom|center_vertical" android:layout_marginTop="10dip"> <ImageView android:layout_width="50dip" android:layout_height="50dip" android:src="@mipmap/ic_source"/> <EditText android:id="@+id/sourceAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Source Address" android:textSize="16dip" android:layout_marginLeft="5dip" android:inputType="textMultiLine" android:focusable="false"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="bottom|center_vertical" android:layout_marginTop="10dip"> <ImageView android:layout_width="50dip" android:layout_height="50dip" android:src="@mipmap/ic_destination"/> <EditText android:id="@+id/destinationAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Destination Address" android:textSize="16dip" android:layout_marginLeft="5dip" android:inputType="textMultiLine" android:focusable="false"/> </LinearLayout> <Button android:id="@+id/btnRoute" android:layout_width="140dip" android:layout_height="45dip" android:background="#000000" android:text="Show Route" android:textColor="#ffffff" android:gravity="center" android:layout_marginTop="20dip" android:layout_gravity="center_horizontal" android:textAllCaps="false" android:textSize="16dip"/> </LinearLayout>

5. Now open MainActivity.java and add the below code.

								
package com.androidlearningtutorials.route; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlaceAutocomplete; import java.util.Locale; public class MainActivity extends AppCompatActivity { EditText sourceAddress, destinationAddress; Button btnRoute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sourceAddress = (EditText)findViewById(R.id.sourceAddress); destinationAddress = (EditText)findViewById(R.id.destinationAddress); btnRoute = (Button)findViewById(R.id.btnRoute); sourceAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) .build(MainActivity.this); startActivityForResult(intent, 100); } catch (GooglePlayServicesRepairableException e) { // Handle the error. } catch (GooglePlayServicesNotAvailableException e) { // Handle the error. } } }); destinationAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) .build(MainActivity.this); startActivityForResult(intent, 101); } catch (GooglePlayServicesRepairableException e) { // Handle the error. } catch (GooglePlayServicesNotAvailableException e) { // Handle the error. } } }); btnRoute.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try{ String google_url = "http://maps.google.com/maps?saddr="+sourceAddress.getText().toString()+"&daddr="+destinationAddress.getText().toString(); String uri = String.format(Locale.ENGLISH, google_url, "Where the party is at"); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+latitude+","+longitude+"&daddr=28.6531,77.4280")); intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"); startActivity(intent); }catch (Exception ev){ System.out.print(ev.getMessage()); } } }); } // A place has been received; use requestCode to track the request. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 100 && resultCode == RESULT_OK) { // retrive the data by using getPlace() method. Place place = PlaceAutocomplete.getPlace(this, data); Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber()); sourceAddress.setText(place.getAddress().toString()); } else if (requestCode == 101 && resultCode == RESULT_OK) { // retrive the data by using getPlace() method. Place place = PlaceAutocomplete.getPlace(this, data); Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber()); destinationAddress.setText(place.getAddress().toString()); } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) { Status status = PlaceAutocomplete.getStatus(this, data); // TODO: Handle the error. Log.e("Tag", status.getStatusMessage()); Toast.makeText(MainActivity.this,"GPS not working..",Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { // The user canceled the operation. Toast.makeText(MainActivity.this,"The user canceled the operation.",Toast.LENGTH_LONG).show(); } } }

5. Run your application Output as below.


Dheerendra Singh

Dheerendra Singh is a Mobile Developer(Android) & Web Developer(PHP) of Amisun IT Solutions, Master degree in Computer Science.


About Us

Amisun IT Solutions is an expert Software Development Company giving complete IT arrangements and going about as a seaward improvement community for abroad advancement firms.

We are an imaginative organization, situated in India that gives a progression of Web-based programming applications that have helped clients make fruitful online activities.

Our group of forward masterminds and reforming individuals tries to furnish you with the best of arrangements with flawlessness second to none. Our key concentration is dependably to furnish you with solid arrangements which are precisely planned and planned with stringent quality principles. ...   

Read more

Address

Shoppers Square Mall Shop No. 17 & 18, First Floor,
Shoppers Square Mall, Budhh Prakash Garg Marg, Block 14, Sector 10,
Raj Nagar, Ghaziabad, Uttar Pradesh 201002
P: (+91) 9899776200, (+91) 9899773200