Monday, March 22, 2010

Sample Google Map Driving Direction.

1. Create a Customized Overlay Components.
2. Create a Map View Layout.
3. Get the Direction Data using the google Service.
4. Parse the Data and Generate geopoints
5. Draw the path using the customized Overlay Components


Create a Customized Overlay Components.
This components are used to draw the rount, which extends the overlay class.
Reference : http://about-android.blogspot.com/2010/03/steps-to-place-marker-in-map-overlay.html

Create a Map View Layou
t
Create a Map View and add create a mainactivity.
Reference :http://about-android.blogspot.com/2010/02/map-implementation.html

Get the Direction Data using the google Service
Google provides the varity of service to access the google map. In this blog we are using the following service to get the direction data.
http://maps.google.com/maps?f=d&hl=en&saddr=XXXXXXX&daddr=XXXXXXX&ie=UTF8&0&om=0&output=kml
Reference : http://mapki.com/wiki/Google_Map_Parameters

String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="+srcPlace+"&daddr="+destPlace+"&ie=UTF8&0&om=0&output=kml";       
    HttpURLConnection urlConnection = null;
    URL url = null;
    String pathConent = "";
    try {
        url = new URL(urlString.toString());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
        InoutStream is =  urlConnection.getInputStream();
    } catch (Exception e) {
    }


Parse the Data and Generate geopoints
Here i am using the DOM Parser for parse the Content. You can use SAX parser.

Reference : http://about-android.blogspot.com/2010/02/sample-saxparser-in-android.html

Sample DOM Parser:
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    doc = db.parse(urlConnection.getInputStream());
    NodeList nl = doc.getElementsByTagName("LineString");
    for (int s = 0; s < nl.getLength(); s++) {
        Node rootNode = nl.item(s);
        NodeList configItems = rootNode.getChildNodes();
        for (int x = 0; x < configItems.getLength(); x++) {
            Node lineStringNode = configItems.item(x);
            NodeList path = lineStringNode.getChildNodes();
            pathConent = path.item(0).getNodeValue();
        }
    }




The following method is used to access the Url and parse content


private String[] getDirectionData(String srcPlace, String destPlace) {

    String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
            + srcPlace + "&daddr=" + destPlace
            + "&ie=UTF8&0&om=0&output=kml";
    Log.d("URL", urlString);
    Document doc = null;
    HttpURLConnection urlConnection = null;
    URL url = null;
    String pathConent = "";
    try {

        url = new URL(urlString.toString());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(urlConnection.getInputStream());

    } catch (Exception e) {
    }

    NodeList nl = doc.getElementsByTagName("LineString");
    for (int s = 0; s < nl.getLength(); s++) {
        Node rootNode = nl.item(s);
        NodeList configItems = rootNode.getChildNodes();
        for (int x = 0; x < configItems.getLength(); x++) {
            Node lineStringNode = configItems.item(x);
            NodeList path = lineStringNode.getChildNodes();
            pathConent = path.item(0).getNodeValue();
        }
    }
    String[] tempContent = pathConent.split(" ");
    return tempContent;
}


Draw the path using the customized Overlay Components
Using the Custom Overlay Component we can draw the line.

    // STARTING POINT
    GeoPoint startGP = new GeoPoint(
            (int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
                    .parseDouble(lngLat[0]) * 1E6));

    myMC = myMapView.getController();
    geoPoint = startGP;
    myMC.setCenter(geoPoint);
    myMC.setZoom(15);
    myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));

    // NAVIGATE THE PATH
    GeoPoint gp1;
    GeoPoint gp2 = startGP;

    for (int i = 1; i < pairs.length; i++) {
        lngLat = pairs[i].split(",");
        gp1 = gp2;
        // watch out! For GeoPoint, first:latitude, second:longitude
        gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
                (int) (Double.parseDouble(lngLat[0]) * 1E6));
        myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
        Log.d("xxx", "pair:" + pairs[i]);
    }

    // END POINT
    myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));


Sample Source


Custom Overlay Component : [DirectionPathOverlay.java]

public class DirectionPathOverlay extends Overlay {
    private GeoPoint gp1;
    private GeoPoint gp2;
    public DirectionPathOverlay(GeoPoint gp1, GeoPoint gp2) {
        this.gp1 = gp1;
        this.gp2 = gp2;
    }

    @Override
    public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
            long when) {
        // TODO Auto-generated method stub
        Projection projection = mapView.getProjection();
        if (shadow == false) {
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            Point point = new Point();
            projection.toPixels(gp1, point);
            paint.setColor(Color.BLUE);
            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(2);
            canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
                    (float) point2.y, paint);
        }
        return super.draw(canvas, mapView, shadow, when);
    }

    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow) {
        // TODO Auto-generated method stub

        super.draw(canvas, mapView, shadow);
    }

}



MainAcvity.java

public class MainActivity extends MapActivity {
    MapView myMapView = null;
    MapController myMC = null;
    GeoPoint geoPoint = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myMapView = (MapView) findViewById(R.id.mapid);
        geoPoint = null;
        myMapView.setSatellite(false);

        String pairs[] = getDirectionData("trichy", "thanjavur");
        String[] lngLat = pairs[0].split(",");

        // STARTING POINT
        GeoPoint startGP = new GeoPoint(
                (int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
                        .parseDouble(lngLat[0]) * 1E6));

        myMC = myMapView.getController();
        geoPoint = startGP;
        myMC.setCenter(geoPoint);
        myMC.setZoom(15);
        myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));

        // NAVIGATE THE PATH
        GeoPoint gp1;
        GeoPoint gp2 = startGP;

        for (int i = 1; i < pairs.length; i++) {
            lngLat = pairs[i].split(",");
            gp1 = gp2;
            // watch out! For GeoPoint, first:latitude, second:longitude
            gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
                    (int) (Double.parseDouble(lngLat[0]) * 1E6));
            myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
            Log.d("xxx", "pair:" + pairs[i]);
        }

        // END POINT
        myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));

        myMapView.getController().animateTo(startGP);
        myMapView.setBuiltInZoomControls(true);
        myMapView.displayZoomControls(true);

    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

    private String[] getDirectionData(String srcPlace, String destPlace) {

        String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
                + srcPlace + "&daddr=" + destPlace
                + "&ie=UTF8&0&om=0&output=kml";
        Log.d("URL", urlString);
        Document doc = null;
        HttpURLConnection urlConnection = null;
        URL url = null;
        String pathConent = "";
        try {

            url = new URL(urlString.toString());
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.connect();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(urlConnection.getInputStream());

        } catch (Exception e) {
        }

        NodeList nl = doc.getElementsByTagName("LineString");
        for (int s = 0; s < nl.getLength(); s++) {
            Node rootNode = nl.item(s);
            NodeList configItems = rootNode.getChildNodes();
            for (int x = 0; x < configItems.getLength(); x++) {
                Node lineStringNode = configItems.item(x);
                NodeList path = lineStringNode.getChildNodes();
                pathConent = path.item(0).getNodeValue();
            }
        }
        String[] tempContent = pathConent.split(" ");
        return tempContent;
    }

}


73 comments:

  1. your tutorials are very useful.... thanks for sharing your knowledge..... Keep it up....

    ReplyDelete
  2. tutorial was awesome now my problem is

    i want to get directions using lat and long values

    so in my case i have four values

    starting lat,long
    end lat , long

    could you please guide can i get directions using these values or not?

    thanks in advance

    ReplyDelete
  3. Thank you so much for ur solution
    it really help me a lot.
    Thanks again

    ReplyDelete
    Replies
    1. hi
      please help us
      i want ready above example
      if you have then plz send me mayank.langalia@live.com

      Delete
  4. i don't know how to obtain travelling mode ? examples are walking ,transist or driving mode ?
    thank U very much !

    ReplyDelete
  5. http://mirnauman.wordpress.com/2012/04/26/android-google-maps-tutorial-part-7-drawing-a-path-or-line-between-two-locations/

    this tutorial makes it very easy to draw lines on google maps

    ReplyDelete
  6. thank you so much for this nice tutorials.

    ReplyDelete
  7. Nice tutorial. Can you tell me how to draw pins at nodes(waypoints) and show the location description on click of it.

    ReplyDelete
  8. kml file is not downloadable anymore from Google..
    Can you please modify the code as per xml file.
    I am in urgent need of that. I was using kml file output only and it was working fine till 27th july 2012 but it has stopped now and I urgently need to correct my code.
    Can yoou please show me a code working on xml format and mail me at pankaj_88_88@yahoo.com

    ReplyDelete
    Replies
    1. Dear Pankaj Kushwaha,
      Salam Alikom, Hope u r fine. I spent along time in this problem till I got this link its very very helpfull,
      Link -- > http://stackoverflow.com/questions/11323500/google-maps-api-version-difference
      MAin Idea of this Solutionis>> KML is not supported anymore, So move to JSON which means download JSON format instead KML, then parse it to get list of GEOpoints on the road and finally draw it.

      Delete
  9. nice tutorial. but unfortunately, the KML file isn't available anymore on google. I'm now struggling with JSON to extract the lat and long from the polyline to draw the path. It would be nice if there was someone who's already done it and made a tutorial.

    ReplyDelete
  10. KML file isn't downloadable anymore. Everyone has another way to do this, help me ...

    ReplyDelete
  11. can u provide a tutorial for find route map between two given location .here we enter two locations in one screen and submit those places then show the route map from source to destination....i am trying hardly but its not come....
    can u help me?

    ReplyDelete
  12. The URL http://maps.google.com/maps?f=d&hl=en&saddr=XXXXXXX&daddr=XXXXXXX&ie=UTF8&0&om=0&output=kml is not working now

    ReplyDelete
  13. ok now I got it by using Json on link that is supplied by Google API, everyone can use it

    ReplyDelete
  14. i want to use google places api to find nearby places.. can u plz share sm links or examples..

    ReplyDelete
  15. hi current am working on google maps to track the user ....

    anyone plz help me its very urgent for me
    my contact no:9030189921
    prasannadavu4@gmail.com

    ReplyDelete
  16. Thanks for sharing Information.

    Driving Training India offers driving training by experience expertise. In whole session of training our expertise guide all the rules and regulations of traffic and make the perfect. Hence, when deal with number of vehicle manage by own terms and conditions.

    ReplyDelete
  17. How can I use Google maps to find nearest hospitals or schools?

    ReplyDelete
    Replies
    1. http://stackoverflow.com/questions/8428209/show-current-location-and-nearby-places-and-route-between-two-places-using-googl

      Delete
  18. Last month, the California-based internet giant began re-evaluating its user-edited online map system after the latest embarrassing incident -- an image of an Android mascot urinating on an Apple logo. To know more about , Visit Android training in chennai

    ReplyDelete
  19. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.Best Android Training in Velachery | android development course fees in chennai

    ReplyDelete
  20. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.Android Training institute in chennai with placement | Best Android Training in velachery

    ReplyDelete
  21. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    Selenium Training in Chennai | Selenium Training in Bangalore | Selenium Training in Pune

    ReplyDelete
  22. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    Selenium Training in Chennai | Selenium Training in Bangalore | Selenium Training in Pune

    ReplyDelete
  23. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.
    rpa training in chennai
    rpa training in bangalore
    rpa course in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  24. Resources like the one you mentioned here will be very useful to me ! I will post a link to this page on my blog. I am sure my visitors will find that very useful
    online Python training
    python training in chennai

    ReplyDelete
  25. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ReplyDelete
  26. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    python interview questions and answers
    python tutorials
    python course institute in electronic city

    ReplyDelete
  27. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    online Python training
    python training in chennai

    ReplyDelete
  28. Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ReplyDelete
  29. Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...
    Online DevOps Certification Course - Gangboard
    Best Devops Training institute in Chennai

    ReplyDelete
  30. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    AWS Training in Bangalore |Best AWS Training Institute in Bangalore BTM, Marathahalli
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR

    ReplyDelete
  31. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
    AWS Interview Questions And Answers | AWS Interviews Questions and Answers for Devops | aws interview questions on ec2
    AWS Interview questions and answers | AWS Interview Question for Freshers
    Amazon web Services Certification Training in Bangalore | AWS Training in Bangalore jayanagar

    ReplyDelete
  32. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage
    contribution from other ones on this subject while our own child is truly discovering a great deal.
    Have fun with the remaining portion of the year.

    Selenium training in bangalore

    ReplyDelete
  33. Very nice post here and thanks for it .I always like and such a super contents of these post.
    Excellent and very cool idea and great content of different kinds of the valuable information's.
    Java training in Chennai
    Java training in Bangalore
    Java online training
    Java training in Pune

    ReplyDelete
  34. Das Green Valley Inn bietet den besten Urlaub in Belize und Guatemala. Planen und genießen Sie Ihren Urlaub in Belize mit Peter Wolf Reise-Team mit den besten Angeboten.

    Belize Guatemala Reise
    Urlaub in Belize

    ReplyDelete
  35. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    microsoft azure training in bangalore
    rpa training in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete

  36. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
    Keep update more information..


    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium interview questions and answers

    ReplyDelete
  37. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..please sharing like this information......
    oneplus mobile service center
    oneplus mobile service centre in chennai
    oneplus mobile service centre
    oneplus service center near me
    oneplus service
    oneplus service centres in chennai
    oneplus service center velachery
    oneplus service center in vadapalani

    ReplyDelete
  38. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Thanks & Regards,
    VRIT Professionals,
    No.1 Leading Web Designing Training Institute In Chennai.

    And also those who are looking for
    Web Designing Training Institute in Chennai
    SEO Training Institute in Chennai
    Photoshop Training Institute in Chennai
    PHP & Mysql Training Institute in Chennai
    Android Training Institute in Chennai

    ReplyDelete
  39. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information regarding Microsoft Azure which is latest and newest,

    Regards,
    Ramya

    Azure Training in Chennai
    Azure Training Center in Chennai
    Best Azure Training in Chennai
    Azure Devops Training in Chenna
    Azure Training Institute in Chennai
    Azure Training in Chennai OMR
    Azure Training in Chennai Velachery
    Azure Online Training

    ReplyDelete
  40. Whatscr - many peoples want to join random whatsapp groups . as per your demand we are ready to serve you whatsapp group links . On this website you can join unlimited groups . click and get unlimited whatsapp group links

    ReplyDelete
  41. My manju - if you want girls mobile numbers then this website is best for you . you can visit on this website and get their information and you also can meet with thrm and go for a date . click here to use our website --- online dating website

    ReplyDelete
  42. uvoffer- if you are searching for free unlimted tricks then visit now on Uvoffer.com and get unlimited offers and informations.
    film ka naam whatsapp puzzle answer film ka naam whatsapp puzzle

    ReplyDelete
  43. Indian WhatsApp Group Links: Join Indian WhatsApp Groups. Latest whatsapp group links We have 1000+ Latest WhatsApp Indian Groups Links List.

    Nigeria whatsapp chat groups are very much in Nigeria whatsapp groups list demand so thats why we have to add the article about Nigeria whatsapp chat groups links

    ReplyDelete