How to display route between two points (geopoints) on Google Maps in Android

Published by Igor Khrupin on

UPDATE: Now this is not working. Google API changed.

Recently a have some task in my Android project.

I needed to show route (directions) between two points (geopoins)on google maps in Android.

I thought it can be simple task. But It was a lot of interesting things :).

I’ve discovered a lot of topics of this problem.

I find one usefull. This is IT

But, it didn’t works for me.

Here I want to show my changes of this project.

Below you can download source code of sample Android project.

Here is screenshot:

The major changes is in KML parser. Here is this class:

package com.hrupin.maproute.route;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class RoadProvider {
	private static Document xmlDocument;

	public static Road getRoute(InputStream is) {
		Road mRoad = new Road();
		String expression = "string(//Placemark/GeometryCollection/LineString/coordinates)";
		String expression2 = "string(//Placemark[contains(name, 'Route')]/description)";
		try {
			xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
			XPathFactory xPathFactory = XPathFactory.newInstance();
			XPath xPath = xPathFactory.newXPath();
			XPathExpression xPathExpression = xPath.compile(expression);
			String result = xPathExpression.evaluate(xmlDocument);
			String[] arr1 = result.split(" ");
			for (String str : arr1) {
				String[] coords = str.split(",");
				if (coords.length == 3) {
					double[] xy = new double[] {};
					double x = Double.parseDouble(coords[0]);
					double y = Double.parseDouble(coords[1]);

					xy = addDouble(xy, x);
					xy = addDouble(xy, y);
					mRoad.mRoute = addDouble(mRoad.mRoute, xy);
					System.out.println("PARSING ..... ");
				}
			}
			
			xPathExpression = xPath.compile(expression2);
			String description = xPathExpression.evaluate(xmlDocument);
			
			mRoad.mDescription = cleanup(description);
			
			System.out.println("DESCRIPTION = " + mRoad.mDescription);
			
		} catch (Exception ex) {
			ex.printStackTrace();
		} 
		return mRoad;
	}

	static double[][] addDouble(double[][] array, double[] element) {
		int arrayLength = array.length;
		double[][] result = new double[arrayLength + 1][];
		for (int i = 0; i < arrayLength; i++) {
			int elementLength = array[i].length;
			result[i] = new double[elementLength];
			for (int j = 0; j < elementLength; j++)
				result[i][j] = array[i][j];
		}
		int newElementLength = element.length;
		result[arrayLength] = new double[newElementLength];
		for (int j = 0; j < newElementLength; j++)
			result[arrayLength][j] = element[j];
		return result;
	}

	static double[] addDouble(double[] array, double element) {
		int arrayLength = array.length;
		double[] result = new double[arrayLength + 1];
		for (int i = 0; i < arrayLength; i++)
			result[i] = array[i];
		result[arrayLength] = element;
		return result;
	}

	public static String getUrl(double fromLat, double fromLon, double toLat, double toLon) {
		StringBuffer urlString = new StringBuffer();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");
		urlString.append(Double.toString(fromLat));
		urlString.append(",");
		urlString.append(Double.toString(fromLon));
		urlString.append("&daddr=");
		urlString.append(Double.toString(toLat));
		urlString.append(",");
		urlString.append(Double.toString(toLon));
		urlString.append("&ie=UTF8&0&om=0&output=kml");
		return urlString.toString();
	}
	
	private static String cleanup(String value) {
		String remove = "<br/>";
		int index = value.indexOf(remove);
		if (index != -1)
			value = value.substring(0, index);
		remove = "&#160;";
		index = value.indexOf(remove);
		int len = remove.length();
		while (index != -1) {
			value = value.substring(0, index).concat(value.substring(index + len, value.length()));
			index = value.indexOf(remove);
		}
		return value;
	}
}

Enjoy! 🙂

Here you can download the source code of this Android Project.

Download it from github

12 Comments

sandesh · 20 May, 2012 at 17:45

Hi,
Thanks for ur code….I tried it but its not showing the google map when i load it in my android mobile nor in the emulator….
I m getting only red line showing the route but no google map in background….can u please help….

Thanks in advance….

Regards,
Sandesh

Ameni · 3 July, 2012 at 12:45

hi sandesh,
you are propebly forgot to add the API key to the main.xml
you must insert the Google tag with the api key like shown bellow :

sudheer · 10 August, 2012 at 13:30

for me this is not working. i m getting null pointer exception at mRoad.getSize

Igor · 10 August, 2012 at 17:41

Hello sudheer,
Now it is not working. Google changed API.

Ameni · 11 August, 2012 at 00:56

yeap ! the API has changed ..
in fact the KML file is not fonctionable anymore you must use XML or JASON to parse the data
for example try to use this URL :” http://maps.google.com/maps/api/directions/xml?origin=50.06469,19.944788&destination=50.064001,19.92039&sensor=true&mode=driving
it will lead you to the web service of google map
so that you can parse it with XML parser like : DOM Parser

prasad · 14 August, 2012 at 11:56

brother can u help me in changing the images in a gridview dynamically

Igor · 14 August, 2012 at 17:20

Hello prasad,
you wrote: brother can u help me in changing the images in a gridview dynamically

Please, describe application workflow.

prasad · 14 August, 2012 at 18:27

my app is there is a home page with a menu button and back button.When we click the menu button a grid view comes with images and textview.These images have their on clicks to certain webpages.For eg if we click the home image it will go to the home page,if we click travel it goes to travel page.If we are in the home page ,or travel page menu button will be at the top with click as gridview.The problem is that if we are in the home page we should not be able to click on the home image,we should disable onclick on that image,and also we have to change the image ,like wise if we are in travel page travle should be disabled.i think u got idea what i meant ,plz help me bro in that

Nova · 23 August, 2012 at 10:10

Very good article! Thank you Igor!!!
But as you know it is not working now, because Google changed API and didn’t write to us )) Tell me please, are you going to update the post this month? Thank you!

Igor · 23 August, 2012 at 15:29

Hello Nova,
Yes, I going to update this post during 4-5 days.

Nirav · 24 August, 2012 at 21:55

I wanna put current location in my google project in Android. And one textview(baloon) on current location tip showing that “click here” message, on clicking that, menu will be displayed for say,
1. get nearest stop
2. get distance t the stop
3. get time schedule

Can anyone help me out..??

    hisham · 6 March, 2014 at 01:34

    please Nirav , i need your help !
    please contact me as soon as !

Leave a Reply to prasad Cancel reply

Avatar placeholder

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.