views:

671

answers:

2

At the moment I am using this code to inquire google maps for directions from an address to another one, then I simply draw it on a mapview from its GeometryCollection. But yet this isn't enough I need also to extract the total expected duration from the kml. can someone give a little sample code to help me? thanks

StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
//Log.d("xxx","URL="+urlString.toString());
// get the kml (XML) doc. And parse it to get the coordinates(direction route).
Document doc = null;
HttpURLConnection urlConnection= null;
URL url = null;
try
{
    url = new URL(urlString.toString());
    urlConnection=(HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.connect();
    dbf = DocumentBuilderFactory.newInstance();
    db = dbf.newDocumentBuilder();
    doc = db.parse(urlConnection.getInputStream());
    if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
    {
        //String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
        String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
        //Log.d("xxx","path="+ path);
        String[] pairs = path.split(" ");
        String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
        // src
        GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
        mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
        GeoPoint gp1;
        GeoPoint gp2 = startGP;
        for(int i=1;i<pairs.length;i++) // the last one would be crash
        {
            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));
            mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
            //Log.d("xxx","pair:" + pairs[i]);
        }
        mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
        }
    }catch (MalformedURLException e){
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }catch (SAXException e){
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}
+2  A: 

Use the new Directions api. The duration is returned in the response and no more parsing of KML, which I think breaks the Google maps license terms anyways.

Update. Ok use the JSON output, with it parsing is built into Android.

Ex url: http://maps.google.com/maps/api/directions/json?origin=Chicago,IL&amp;destination=Los+Angeles,CA&amp;waypoints=Joplin,MO|Oklahoma+City,OK&amp;sensor=false

Response is

{
  "status": "OK",
  "routes": [ {
    "summary": "I-40 W",
    "legs": [ {
      "steps": [ {
        "travel_mode": "DRIVING",
        "start_location": {
          "lat": 41.8507300,
          "lng": -87.6512600
        },
        "end_location": {
          "lat": 41.8525800,
          "lng": -87.6514100
        },
        "polyline": {
          "points": "a~l~Fjk~uOwHJy@P",
          "levels": "B?B"
        },
        "duration": {
          "value": 19,
          "text": "1 min"
        },
        "html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e",
        "distance": {
          "value": 207,
          "text": "0.1 mi"
        }
      },
      ...
      ... additional steps of this leg
    ...
    ... additional legs of this route
      "duration": {
        "value": 74384,
        "text": "20 hours 40 mins"
      },
      "distance": {
        "value": 2137146,
        "text": "1,328 mi"
      },
      "start_location": {
        "lat": 35.4675602,
        "lng": -97.5164276
      },
      "end_location": {
        "lat": 34.0522342,
        "lng": -118.2436849
      },
      "start_address": "Oklahoma City, OK, USA",
      "end_address": "Los Angeles, CA, USA"
    } ],
    "copyrights": "Map data ©2010 Google, Sanborn",
    "overview_polyline": {
      "points": "a~l~Fjk~uOnzh@vlbBtc~@tsE`vnApw{A`dw@~w\\|tNtqf@l{Yd_Fblh@rxo@b}@xxSfytAblk@xxaBeJxlcBb~t@zbh@jc|Bx}C`rv@rw|@rlhA~dVzeo@vrSnc}Axf]fjz@xfFbw~@dz{A~d{A|zOxbrBbdUvpo@`cFp~xBc`Hk@nurDznmFfwMbwz@bbl@lq~@loPpxq@bw_@v|{CbtY~jGqeMb{iF|n\\~mbDzeVh_Wr|Efc\\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg@|kHntyArpb@bijCk_Kv~eGyqTj_|@`uV`k|DcsNdwxAott@r}q@_gc@nu`CnvHx`k@dse@j|p@zpiAp|gEicy@`omFvaErfo@igQxnlApqGze~AsyRzrjAb__@ftyB}pIlo_BflmA~yQftNboWzoAlzp@mz`@|}_@fda@jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC",
      "levels": "BBBAAAAABAABAAAAAABBAAABBAAAABBAAABABAAABABBAABAABAAAABABABABBABAABB"
    },
    "warnings": [ ],
    "waypoint_order": [ 0, 1 ]
  } ]
} 

Let's say you used the standard http client libraries and now have the response in a String.

JSONObject jsonObject = new JSONObject(response); // parse response into json object
JSONObject routeObject = jsonObject.getJSONObject("route"); // pull out the "route" object
JSONObject durationObject = jsonObject.getJSONObject("duration"); // pull out the "duration" object
String duration = durationObject.getString("text"); //this should be the duration text value (20 hours 40 mins)

You will have to wrap all that in a try-catch block to catch the JSONExceptions.

BrennaSoft
ok I read this page http://code.google.com/apis/maps/documentation/directions/#XMLwhich contains the explanation what I don't know now is how to interpret this file: by this I mean as for the kml there is a tag GeometryCollection containing the route know how to draw it in the map.and what is this <overview_polyline> <points> ** human unreadble String**</points> ... </overview_polyline> thanks
urobo
Updated to show example.
BrennaSoft
A: 

You might find this useful:

http://home.ameliemedia.com/android-app-aroundme/#tips

(from http://stackoverflow.com/questions/2853017/android-google-directions)

Steve
the first link provides an implementation breaking the google maps tos, which is the same I gave. while the second opens simply maps I have to handle maps events also add and remove overlays, prompt application alerts... there is a way to do it within the Maps app?
urobo
You're absolutely right, the ameliemedia code does not use the Directions API as I thought it would.There is no way I know of to obtain that level of control over the Maps app. You'll need to write code to parse and render the data returned from the Directions API, as Rpond correctly explained.
Steve