Search code examples
javaandroidjsongoogle-mapsgoogle-directions-api

How to parse Directions API Response from my middleware in android?


how do I parse the API response of Google Directions API to draw a route from my point A to point B? I get my API response from my web's middleware. Do I need to create a POJO for this? is RoboPOJOgenerator a good one to use in making POJO from json? This json is the response from my okhttp logger.

{
"data":[
  {
     "bounds":{
        "northeast":{
           "lat":14.5845178,
           "lng":121.0601253
        },
        "southwest":{
           "lat":14.5722047,
           "lng":121.0535383
        }
     },
     "copyrights":"Map data \u00a92019",
     "legs":[
        {
           "distance":{
              "text":"2.0 km",
              "value":2013
           },
           "duration":{
              "text":"11 mins",
              "value":638
           },
           "end_address":"J Vargas Bus Stop, Epifanio de los Santos, Ortigas Center, Mandaluyong, Metro Manila, Philippines",
           "end_location":{
              "lat":14.5845178,
              "lng":121.0569895
           },
           "start_address":"14/F Robinsons Cybergate Tower 1 Pioneer St. Metro Manila, Philippines",
           "start_location":{
              "lat":14.5722047,
              "lng":121.0540196
           },
           "steps":[
              {
                 "distance":{
                    "text":"70 m",
                    "value":70
                 },
                 "duration":{
                    "text":"1 min",
                    "value":13
                 },
                 "end_location":{
                    "lat":14.5725109,
                    "lng":121.0545851
                 },
                 "html_instructions":"Head <b>northeast</b> on <b>Pioneer St</b> toward <b>Reliance St</b><div style=\"font-size:0.9em\">Pass by HMR Trading Haus (on the left)</div>",
                 "polyline":{
                    "points":"gc}wAsjzaV]q@Ug@IW"
                 },
                 "start_location":{
                    "lat":14.5722047,
                    "lng":121.0540196
                 },
                 "travel_mode":"DRIVING"
              },
              {
                 "distance":{
                    "text":"0.2 km",
                    "value":210
                 },
                 "duration":{
                    "text":"1 min",
                    "value":42
                 },
                 "end_location":{
                    "lat":14.5741085,
                    "lng":121.0535383
                 },
                 "html_instructions":"Turn <b>left</b> onto <b>Reliance St</b>",
                 "maneuver":"turn-left",
                 "polyline":{
                    "points":"ee}wAenzaVmBhAmAp@cCtA"
                 },
                 "start_location":{
                    "lat":14.5725109,
                    "lng":121.0545851
                 },
                 "travel_mode":"DRIVING"
              },
              {
                 "distance":{
                    "text":"0.6 km",
                    "value":573
                 },
                 "duration":{
                    "text":"3 mins",
                    "value":159
                 },
                 "end_location":{
                    "lat":14.5780025,
                    "lng":121.0569962
                 },
                 "html_instructions":"Turn <b>right</b> onto <b>Sheridan</b>",
                 "maneuver":"turn-right",
                 "polyline":{
                    "points":"eo}wAsgzaVU_@Yg@GKKKECeCwB_ByAu@s@YWuAcAqCmB[UWQ}@o@o@g@"
                 },
                 "start_location":{
                    "lat":14.5741085,
                    "lng":121.0535383
                 },
                 "travel_mode":"DRIVING"
              },
              {
                 "distance":{
                    "text":"0.8 km",
                    "value":829
                 },
                 "duration":{
                    "text":"6 mins",
                    "value":336
                 },
                 "end_location":{
                    "lat":14.5843678,
                    "lng":121.0599721
                 },
                 "html_instructions":"Continue onto <b>San Miguel Ave</b>",
                 "polyline":{
                    "points":"og~wAg}zaVOi@OMYWKGq@e@KIm@a@[SYSCAy@k@}@m@WSe@_@WOeAw@]Uw@m@}BgBKGQKMCMCM@S?_@BQ@G?y@BkAFw@?S?YBq@@S@}AB"
                 },
                 "start_location":{
                    "lat":14.5780025,
                    "lng":121.0569962
                 },
                 "travel_mode":"DRIVING"
              },
              {
                 "distance":{
                    "text":"0.3 km",
                    "value":331
                 },
                 "duration":{
                    "text":"1 min",
                    "value":88
                 },
                 "end_location":{
                    "lat":14.5845178,
                    "lng":121.0569895
                 },
                 "html_instructions":"Turn <b>left</b> onto <b>Do\u00f1a Julia Vargas Ave</b><div style=\"font-size:0.9em\">Destination will be on the right</div>",
                 "maneuver":"turn-left",
                 "polyline":{
                    "points":"io_xAyo{aVS@?PAd@?b@?\\AxEA`A?RA\\AlB?Z"
                 },
                 "start_location":{
                    "lat":14.5843678,
                    "lng":121.0599721
                 },
                 "travel_mode":"DRIVING"
              }
           ],
           "traffic_speed_entry":[

           ],
           "via_waypoint":[

           ]
        }
     ],
     "overview_polyline":{
        "points":"gc}wAsjzaVs@yAIWmBhAqEfCo@gASWkC{BuCmCoB{AcGeEo@g@Oi@i@e@wByAsBuAsCqByGcF]S[GsAFaABkAFw@?m@BeABqBDAv@C|ICzD"
     },
     "summary":"Sheridan and San Miguel Ave",
     "warnings":[

     ],
     "waypoint_order":[

     ]
  }
],
"status":"SUCCESS"
}

That is my response coming from the middle ware, I cannot use this code below

 private String getRequestUrl(LatLng origin, LatLng dest) {
    String str_org = "origin=" + origin.latitude + "," + origin.longitude;
    String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
    String sensor = "sensor=false";
    String mode = "mode=driving";
    String avoid = "avoid=tolls|highways";
    String param = str_org + "&" + str_dest + "&" + sensor + "&" + mode + "&" + avoid;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + param + "&key=" + getString(R.string.API_KEY);

    return url;
}

private String requestDirection(String reqUrl) throws IOException {
    String responseString = "";
    InputStream inputStream = null;
    HttpURLConnection httpURLConnection = null;
    try {
        URL url = new URL(reqUrl);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();

        //Get the response result
        inputStream = httpURLConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        StringBuffer stringBuffer = new StringBuffer();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }

        responseString = stringBuffer.toString();
        bufferedReader.close();
        inputStreamReader.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        httpURLConnection.disconnect();
    }
    return responseString;
}

because I am not accessing the Directions API in my mobile app, I access it through my web's middleware. I really need help I've been stuck with this problem for 3 days now. Sorry for asking too many questions.


Solution

  • How do I parse the API response of Google Directions API to draw a route from my point A to point B?

    The API response is an array of small trips. You can imagine it as Google maps app giving you some sort of feedback every time that you arrive at the end of each step. Otherwise, I think the API structure is quite clear and field names describe their meaning quite clear. Let me know if you need me to go over them in more detail.

    I get my API response from my web's middleware. Do I need to create a POJO for this.

    You should definitely use a POJO (in other words, a DTO) here. The data is clearly defined and structured and a java object is much easier to navigate and utilize than wandering around JsonNode's. You will also have to deal with lots of different scenarios when your user uses the navigation (changing route, losing connection, app going to sleep) so you will have to continuously re-query the said data to update the map. Not using POJO's would set you up for a LOT of trouble and smelly code.

    Is RoboPOJOgenerator a good one to use in making POJO from json?

    Personally I like to use http://www.jsonschema2pojo.org/ to generate me the domain classes but your suggestion should also be able to do the same thing.