Android Draw route between two geo location MapV2
This post about draw route between two geo location using
google map V2.
When I use the google map V2 its loading two fast.
I hope this post helpful for you
Screen Shot
Activity Source Code
package
com.androidbunch.drawroutev2;
import
java.util.ArrayList;
import java.util.List;
import
org.w3c.dom.Document;
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.MarkerOptions;
import
com.google.android.gms.maps.model.PolylineOptions;
import
com.google.android.maps.GeoPoint;
import
com.google.android.maps.Overlay;
import
android.location.Location;
import
android.location.LocationManager;
import
android.os.AsyncTask;
import
android.os.Bundle;
import
android.app.ProgressDialog;
import
android.graphics.Color;
import
android.graphics.drawable.Drawable;
import
android.support.v4.app.FragmentActivity;
/**
*
* @author VIJAYAKUMAR M
*This class for display route current location
to hotel location on google map V2
*/
public class MainActivity extends
FragmentActivity {
List<Overlay>
mapOverlays;
GeoPoint
point1, point2;
LocationManager
locManager;
Drawable
drawable;
Document
document;
GMapV2GetRouteDirection
v2GetRouteDirection;
LatLng
fromPosition;
LatLng
toPosition;
GoogleMap
mGoogleMap;
MarkerOptions
markerOptions;
Location
location ;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v2GetRouteDirection = new
GMapV2GetRouteDirection();
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mGoogleMap =
supportMapFragment.getMap();
// Enabling
MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
mGoogleMap.setTrafficEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
markerOptions = new
MarkerOptions();
fromPosition = new
LatLng(11.663837, 78.147297);
toPosition = new
LatLng(11.723512, 78.466287);
GetRouteTask
getRoute = new GetRouteTask();
getRoute.execute();
}
/**
*
* @author VIJAYAKUMAR M
* This class Get Route
on the map
*
*/
private class GetRouteTask extends
AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String
response = "";
@Override
protected void onPreExecute()
{
Dialog = new
ProgressDialog(MainActivity.this);
Dialog.setMessage("Loading
route...");
Dialog.show();
}
@Override
protected String
doInBackground(String... urls) {
//Get All
Route values
document = v2GetRouteDirection.getDocument(fromPosition, toPosition,
GMapV2GetRouteDirection.MODE_DRIVING);
response = "Success";
return response;
}
@Override
protected void
onPostExecute(String result) {
mGoogleMap.clear();
if(response.equalsIgnoreCase("Success")){
ArrayList<LatLng>
directionPoint = v2GetRouteDirection.getDirection(document);
PolylineOptions
rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i <
directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding
route on the map
mGoogleMap.addPolyline(rectLine);
markerOptions.position(toPosition);
markerOptions.draggable(true);
mGoogleMap.addMarker(markerOptions);
}
Dialog.dismiss();
}
}
@Override
protected void onStop() {
super.onStop();
finish();
}
}
Draw Route Helper Class
package
com.androidbunch.drawroutev2;
import
java.io.InputStream;
import
java.util.ArrayList;
import
javax.xml.parsers.DocumentBuilder;
import
javax.xml.parsers.DocumentBuilderFactory;
import
org.apache.http.HttpResponse;
import
org.apache.http.client.HttpClient;
import
org.apache.http.client.methods.HttpPost;
import
org.apache.http.impl.client.DefaultHttpClient;
import
org.apache.http.protocol.BasicHttpContext;
import
org.apache.http.protocol.HttpContext;
import
org.w3c.dom.Document;
import
org.w3c.dom.Node;
import
org.w3c.dom.NodeList;
import
com.google.android.gms.maps.model.LatLng;
import
android.util.Log;
public class
GMapV2GetRouteDirection {
public final static String MODE_DRIVING = "driving";
public final static String MODE_WALKING = "walking";
public
GMapV2GetRouteDirection() { }
public Document
getDocument(LatLng start, LatLng end, String mode) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=driving";
try {
HttpClient httpClient = new
DefaultHttpClient();
HttpContext localContext = new
BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost,
localContext);
InputStream in =
response.getEntity().getContent();
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String
getDurationText (Document doc) {
NodeList nl1 =
doc.getElementsByTagName("duration");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2,
"text"));
Log.i("DurationText",
node2.getTextContent());
return
node2.getTextContent();
}
public int getDurationValue
(Document doc) {
NodeList nl1 =
doc.getElementsByTagName("duration");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2,
"value"));
Log.i("DurationValue",
node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
}
public String
getDistanceText (Document doc) {
NodeList nl1 =
doc.getElementsByTagName("distance");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2,
"text"));
Log.i("DistanceText",
node2.getTextContent());
return
node2.getTextContent();
}
public int
getDistanceValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2,
"value"));
Log.i("DistanceValue",
node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
}
public String
getStartAddress (Document doc) {
NodeList nl1 =
doc.getElementsByTagName("start_address");
Node node1 = nl1.item(0);
Log.i("StartAddress", node1.getTextContent());
return
node1.getTextContent();
}
public String
getEndAddress (Document doc) {
NodeList nl1 =
doc.getElementsByTagName("end_address");
Node node1 = nl1.item(0);
Log.i("StartAddress",
node1.getTextContent());
return
node1.getTextContent();
}
public String
getCopyRights (Document doc) {
NodeList nl1 =
doc.getElementsByTagName("copyrights");
Node node1 = nl1.item(0);
Log.i("CopyRights",
node1.getTextContent());
return
node1.getTextContent();
}
public
ArrayList<LatLng> getDirection (Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<LatLng> listGeopoints =
new
ArrayList<LatLng>();
nl1 = doc.getElementsByTagName("step");
if (nl1.getLength() > 0) {
for (int i = 0; i <
nl1.getLength(); i++) {
Node node1 = nl1.item(i);
nl2 = node1.getChildNodes();
Node locationNode =
nl2.item(getNodeIndex(nl2, "start_location"));
nl3 =
locationNode.getChildNodes();
Node latNode =
nl3.item(getNodeIndex(nl3, "lat"));
double lat = Double.parseDouble(latNode.getTextContent());
Node lngNode =
nl3.item(getNodeIndex(nl3, "lng"));
double lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat,
lng));
locationNode =
nl2.item(getNodeIndex(nl2, "polyline"));
nl3 =
locationNode.getChildNodes();
latNode =
nl3.item(getNodeIndex(nl3, "points"));
ArrayList<LatLng> arr =
decodePoly(latNode.getTextContent());
for(int j = 0 ; j <
arr.size() ; j++) {
listGeopoints.add(new
LatLng(arr.get(j).latitude, arr.get(j).longitude));
}
locationNode =
nl2.item(getNodeIndex(nl2, "end_location"));
nl3 =
locationNode.getChildNodes();
latNode =
nl3.item(getNodeIndex(nl3, "lat"));
lat = Double.parseDouble(latNode.getTextContent());
lngNode =
nl3.item(getNodeIndex(nl3, "lng"));
lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat,
lng));
}
}
return listGeopoints;
}
private int
getNodeIndex(NodeList nl, String nodename) {
for(int i = 0 ; i <
nl.getLength() ; i++) {
if(nl.item(i).getNodeName().equals(nodename))
return i;
}
return -1;
}
private
ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new
ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index <
len) {
int b, shift = 0,
result = 0;
do {
b = encoded.charAt(index++) -
63;
result |= (b & 0x1f)
<< shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result
& 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) -
63;
result |= (b & 0x1f)
<< shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result
& 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(position);
}
return poly;
}
}
Xml source Code
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_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>
AndroidManifest.xml
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidbunch.drawroutev2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16"
/>
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBE-ZNBoODzqQoA2BMswmoEWAeHMSvgt3M"
/>
<activity
android:name="com.androidbunch.drawroutev2.MainActivity"
android:label="@string/app_name"
android:screenOrientation="landscape"
>
<intent-filter>
<action android:name="android.intent.action.MAIN"
/>
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
<permission
android:name="com.androidbunch.drawroutev2.permission.MAPS_RECEIVE"
android:protectionLevel="signature"
/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"
/>
<uses-permission android:name="com.androidbunch.drawroutev2.permission.MAPS_RECEIVE"
/>
<uses-permission android:name="android.permission.INTERNET"
/>
<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_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
</manifest>
Great Tutorial....Thanks for it...Can you please upload tutorial to draw line on map with user movement?
ReplyDeleteThanks,
DeleteFrom Location you can give your current location mean user movement location.
Actually i want that when user moves from one place to another then line draws on map dynamically. Fro eaxamle as user have to go A to B so it display line with user movement on map (the path user following)instead of showing the direct path between A and B.
DeleteMake it your A point is Current location.
Deletedo i need to use timer to draw line dynamically from point A ( it is my starting point) to point B(its my current location and it is changing continuously as i am moving on map)
Deletehey..please provide me a tutorial for it. i am unable to implement it
DeleteThis comment has been removed by a blog administrator.
ReplyDeleteMay I simply say what a comfort to discover somebody that genuinely understands
ReplyDeletewhat they are discussing over the internet. You definitely realize
how to bring an issue to light and make it important.
More people must check this out and understand this side
of your story. I was surprised you are not more popular given that you definitely possess the gift.
Review my webpage ... www.Durchblick-glasgestaltung.de . Durchblick-glasgestaltung
Great goods from you, man. I've understand your stuff previous to and you are just too wonderful. I really like what you've acquired
ReplyDeletehere, certainly like what you are saying and the way in which you say it.
You make it entertaining and you still take care of to keep it
sensible. I cant wait to read far more from you. This is really a terrific web site.
My webpage; microsoft registry cleaner
I am extremely іnspігed alοng with your
ReplyDeletewriting ѕκіlls and alsο ωith the structure on уοur blοg.
Is this а раid subject mаtteг or ԁіd you customize it your sеlf?
Еithеr wау keеp up the nіcе quality wrіting, it's uncommon to see a great weblog like this one nowadays.. visit the up coming webpage
Your style is unique compared to other folks I've read stuff from. Many thanks for posting when you have the opportunity, Guess I'll
ReplyDeletejust bookmаrk this web ѕite. http://www.pianotut.com/piano-lesson-software/
Hi! Thіs is kind of оff tоpіc
ReplyDeletebut I need sοme guiԁancе from an establishеd blog.
Ιѕ it very difficult to sеt up yοur own blοg?
I'm not very techincal but I can figure things out pretty fast. I'm thinking about setting up
my οwn but I'm not sure where to start. Do you have any ideas or suggestions? With thanks
Take a look at my website - same day long term loans
Sо, questiοn tіme, do I have the opportunity to ask a ԁifficult question?
ReplyDeleteAlso visit my homеpage ... Long Term Loans For Bad Credit No Guarantor No Fee
Haven't heard about this issue before, I ought to do so soon.
ReplyDeleteMy page; get a loan fast
Thanx for uploading such a great tutorial but it gives me two error in main activity one is on "GeoPoint" and other is on "overlay" plz help
ReplyDeleteHi Alam,
DeletePlease download Google service jar file and import it. its for MAP-v2
Hello Vijat, great post.
Deletemy proj is tourist guide wich has three modules i.e. city guider, trek/hiking adviser and tour planner ( dynamically tour plan generation for users) for local tourist companies. can you me in this regard. we will settle matter. pls reply my email or mail me at sp10bcs015@gmail.com
Hello Alam, I'm also got the same error. Overlay and Geopoint classes are not created error. How didi yu solve??
DeleteDiԁ you conѕiԁer your references bеfoге уou wгote all this down?
ReplyDeleteАlѕo vіsit my web-site: best bank loans
I am Extremely Happy to see this blog.this is really helpful and awesome .
ReplyDeleteThank you ashish
Deletehai. Vijay.
DeleteIt's a very helpful post..
But i want to update it.
Like " Actually i want that when user moves from one place to another then line draws on map dynamically. Fro eaxamle as user have to go A to B so it display line with user movement on map (the path user following)instead of showing the direct path between A and B. " .
Thanks in Advance.
U can also Reply to prassad1989@gmail.com
Spur of thе moment artiсlеs are аlωаys the beѕt,
ReplyDeletethе ωriting just flows out οnto the sсreen.
Μy blog post unsecured personal loans
So much for attemptіng thіs myself,
ReplyDeleteI'll never be able to do it. I'll јuѕt reaԁ.
Also viѕit my weblog: fast cash quick
ӏ want to get іt all donе becauѕe I
ReplyDeletewon't have the opportunity to get it done other wise!
My web site; unsecured personal loans
I'm trying to build a similar website to this myself, there's clearly a lot of work thаt goеѕ into it.
ReplyDeleteReally energеtic community as well, which іs
nоt easy to develοp.
Heгe іs my web site; best personal loans
Looks like my ρhone has deсiԁеd to wοrk properlу thiѕ week,
ReplyDeleteI can fіnally seе the rеsponse foгm.
Јust to sаy, I would nоt bоther myself.
My websitе: Best Loans On The Market
ӏ feel аs though I've been on the bad end of a stampeed after reading this. Not easy concentrating with a hangover!
ReplyDeleteHere is my website ... best unsecured loan
Hi,
ReplyDeleteThanks a ton!! Its a great work you have done. I referred your code and it helped me a lot.
thank you
DeleteΗave nοt lοοκеd intο this matter befoгe, I should
ReplyDeletedo so.
Also visit my web blog ... Best loans For Bad credit
its so blοοdy hot.
ReplyDeletemу ωebsite :: personal loans bad credit
Oоh questiοn timе, do I get the opportunity to
ReplyDeleteask you something?
Have a look аt mу web-site - loans broker
Definitelу waѕ nοt the sort of
ReplyDeleteаrticle I was eхpeсting.
my blοg ... unsecured personal loans
Ӏ have spent all of my daу browѕing through all thеse articles.
ReplyDeleteΗοweveг thіs іѕ stіll moгe productive
than yesterdаy was!. Аt leaѕt I'll learn something new.
Feel free to visit my web site - best loan
My api key is alright but still I am getting a blue screen plz do help me what should i do now to resolve this issue
ReplyDeleteStill do you have issue?
DeleteThis comment has been removed by the author.
DeleteMe also have same problem .please can u help to solve this issue?
DeleteThank you so much, you have stated a very high quality material. You helped me a lot.
ReplyDelete(Translation Google)
Hello Sir,
ReplyDeleteI seen your example and as per given your instruction or steps, I have create a new project in my pc, I also create a new api key with v2 and when i do testing i got following error.
Error:
Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
If possible then please give me solution as soon as early.
Great Tutorial
ReplyDeleteThanks so much
Thank you Muhammad
DeleteHi this is ramesh , I am new from android .. how to draw a line from hyderabad to United states of kingdom . . ur coding is working fine with in the country..
ReplyDeletebut not working hyderabad to United States Of kingdom .. Out of memory error(enhaunsed) occured
please help me .. this type of blogs fist time i see , last three month on words i was checking
Why you need Hud to US route?
DeleteYour app requirement
DeleteYou can draw..... because we dont have route.......here to US
Deleteam Asking hyderabad to UK
DeleteHi,I am a android developer i did not yet worked for v2 maps,when i tested it on device it's not working please help me.
ReplyDeleteAPI key is correct ? API key generated with your package name?
DeleteThis comment has been removed by the author.
ReplyDeleteThank you for this tutorial. Whit getDuration, getDistance... methods I get the distance, duration of the first node(item[0]), with Tag "distance" or "duration", but not the total distance or duration.If there are several steps the last is the total value?
ReplyDeleteThanks so much
José Miguel Galache (galachelopez@gmail.com)
Hi VIJAYAKUMAR, I got the error like create class Overlay and create class Geopoint. How do I solve? pls explain
ReplyDeleteWhen you are getting error while import or while debugging?
DeleteHey,, I cleared the error. Its a good example. Thanx for ur blog..
DeleteCheers!!
DeleteTill now i didn't run the application, But Actually i want that when user moves from one place to another place then it will show where we are in line draws on our map. For example as user have to go A to B so it display line with user movement on map (the path user following)instead of showing the direct path between A and B.
DeleteWhat changes will make in your program?
OnLocationChange() call your A point....
DeleteHello VIJAYAKUMAR M. is this code correct? I get an error on manifest file. Can you please help me?
ReplyDeletethank u in advance
good tutorial, it worked, just a query, loading the map puts me in the ocean, I would like to show me the way, how I can do that? Thank you. Greetings from Guatemala.
ReplyDeletevery very good tutorial........ solved my problem completely...... thank you very very much for such a great tutorial
ReplyDeleteThanks for your tutorial, this help my problem.........
ReplyDeleteThanks Bro for this great tutorial
ReplyDeletethanks bro i learn lots of new thing using your code again thanks.........
ReplyDeleteThis comment has been removed by the author.
ReplyDeletegreat ty very much
ReplyDeleteHi!
ReplyDeleteWould you be so kind to provide information what are you doing in helper class? Where I can read about it...
I would really appreciate it!)))Thanks!
I am looking for a programer to develop and android app that receives coordinates from an external program (wireless either bluetooth or wifi) and draw the route in real time in google map. Please contact Simon at simonabadi@hotmail.com
ReplyDeleteThanks. it works
ReplyDeleteIt a great tutorial ,its help me lot ,
ReplyDeletebut there is a one problem in this , if we will use the app without network connection, app will crash ,
plz tell me what is the reason and give some solution for the same.
Thanks in advanced
Hi VIJAYAKUMAR, I got the error like create class Overlay and create class Geopoint. How do I solve? pls explain
ReplyDeleteReply
Thank you
ReplyDeleteI really like your example it help very much i wish good time for you .
Please provide source code.. i can's solve error.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHi
ReplyDeletei have a q? Can we have more them one route on Google map for the same destination and the same position
hosam711@gmail.com