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;
    }

}


21 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