Thursday, April 11, 2013

Android draw route between two geo location MapV2



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>
 



76 comments:

  1. Great Tutorial....Thanks for it...Can you please upload tutorial to draw line on map with user movement?

    ReplyDelete
    Replies
    1. Thanks,
      From Location you can give your current location mean user movement location.

      Delete
    2. 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.

      Delete
    3. Make it your A point is Current location.

      Delete
    4. do 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)

      Delete
    5. hey..please provide me a tutorial for it. i am unable to implement it

      Delete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

  3. Hotels in New DelhiAre you looking for

    Hotels in Delhi? Call cheap hotel in Delhi Today @+91-9810104774 or Hotels in Delhi at

    affordable rates.

    ReplyDelete
  4. May I simply say what a comfort to discover somebody that genuinely understands
    what 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

    ReplyDelete
  5. 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
    here, 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

    ReplyDelete
  6. I am extremely іnspігed alοng with your
    writing ѕκі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

    ReplyDelete
  7. 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
    just bookmаrk this web ѕite. http://www.pianotut.com/piano-lesson-software/

    ReplyDelete
  8. Hi! Thіs is kind of оff tоpіc
    but 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

    ReplyDelete
  9. Sо, questiοn tіme, do I have the opportunity to ask a ԁifficult question?


    Also visit my homеpage ... Long Term Loans For Bad Credit No Guarantor No Fee

    ReplyDelete
  10. Haven't heard about this issue before, I ought to do so soon.

    My page; get a loan fast

    ReplyDelete
  11. 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

    ReplyDelete
    Replies
    1. Hi Alam,
      Please download Google service jar file and import it. its for MAP-v2

      Delete
    2. Hello Vijat, great post.

      my 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

      Delete
    3. Hello Alam, I'm also got the same error. Overlay and Geopoint classes are not created error. How didi yu solve??

      Delete
  12. Diԁ you conѕiԁer your references bеfoге уou wгote all this down?


    Аlѕo vіsit my web-site: best bank loans

    ReplyDelete
  13. I am Extremely Happy to see this blog.this is really helpful and awesome .

    ReplyDelete
    Replies
    1. hai. Vijay.
      It'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

      Delete
  14. Spur of thе moment artiсlеs are аlωаys the beѕt,
    thе ωriting just flows out οnto the sсreen.



    Μy blog post unsecured personal loans

    ReplyDelete
  15. So much for attemptіng thіs myself,
    I'll never be able to do it. I'll јuѕt reaԁ.



    Also viѕit my weblog: fast cash quick

    ReplyDelete
  16. ӏ want to get іt all donе becauѕe I
    won't have the opportunity to get it done other wise!

    My web site; unsecured personal loans

    ReplyDelete
  17. I'm trying to build a similar website to this myself, there's clearly a lot of work thаt goеѕ into it.
    Really energеtic community as well, which іs
    nоt easy to develοp.

    Heгe іs my web site; best personal loans

    ReplyDelete
  18. Looks like my ρhone has deсiԁеd to wοrk properlу thiѕ week,
    I 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

    ReplyDelete
  19. ӏ feel аs though I've been on the bad end of a stampeed after reading this. Not easy concentrating with a hangover!

    Here is my website ... best unsecured loan

    ReplyDelete
  20. Hi,

    Thanks a ton!! Its a great work you have done. I referred your code and it helped me a lot.

    ReplyDelete
  21. Ηave nοt lοοκеd intο this matter befoгe, I should
    do so.

    Also visit my web blog ... Best loans For Bad credit

    ReplyDelete
  22. its so blοοdy hot.

    mу ωebsite :: personal loans bad credit

    ReplyDelete
  23. Oоh questiοn timе, do I get the opportunity to
    ask you something?

    Have a look аt mу web-site - loans broker

    ReplyDelete
  24. Definitelу waѕ nοt the sort of
    аrticle I was eхpeсting.

    my blοg ... unsecured personal loans

    ReplyDelete
  25. Ӏ have spent all of my daу browѕing through all thеse articles.
    Ηο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

    ReplyDelete
  26. 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

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Me also have same problem .please can u help to solve this issue?

      Delete
  27. Thank you so much, you have stated a very high quality material. You helped me a lot.
    (Translation Google)

    ReplyDelete
  28. Hello Sir,

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

    ReplyDelete
  29. Great Tutorial
    Thanks so much

    ReplyDelete
  30. Hi 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..
    but 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

    ReplyDelete
  31. Hi,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.

    ReplyDelete
    Replies
    1. API key is correct ? API key generated with your package name?

      Delete
  32. This comment has been removed by the author.

    ReplyDelete
  33. Thank 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?

    Thanks so much

    José Miguel Galache (galachelopez@gmail.com)

    ReplyDelete
  34. Hi VIJAYAKUMAR, I got the error like create class Overlay and create class Geopoint. How do I solve? pls explain

    ReplyDelete
    Replies
    1. When you are getting error while import or while debugging?

      Delete
    2. Hey,, I cleared the error. Its a good example. Thanx for ur blog..

      Delete
    3. Till 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.
      What changes will make in your program?

      Delete
    4. OnLocationChange() call your A point....

      Delete
  35. Hello VIJAYAKUMAR M. is this code correct? I get an error on manifest file. Can you please help me?
    thank u in advance

    ReplyDelete
  36. 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.

    ReplyDelete
  37. very very good tutorial........ solved my problem completely...... thank you very very much for such a great tutorial

    ReplyDelete
  38. Thanks for your tutorial, this help my problem.........

    ReplyDelete
  39. Thanks Bro for this great tutorial

    ReplyDelete
  40. thanks bro i learn lots of new thing using your code again thanks.........

    ReplyDelete
  41. This comment has been removed by the author.

    ReplyDelete
  42. Hi!

    Would 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!

    ReplyDelete
  43. 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

    ReplyDelete
  44. It a great tutorial ,its help me lot ,
    but 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

    ReplyDelete
  45. Hi VIJAYAKUMAR, I got the error like create class Overlay and create class Geopoint. How do I solve? pls explain

    Reply

    ReplyDelete
  46. Thank you
    I really like your example it help very much i wish good time for you .

    ReplyDelete
  47. Please provide source code.. i can's solve error.

    ReplyDelete
  48. This comment has been removed by the author.

    ReplyDelete
  49. Hi
    i have a q? Can we have more them one route on Google map for the same destination and the same position
    hosam711@gmail.com

    ReplyDelete

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...