DCP

Thursday 13 April 2017

Calling Google Directions API and parsing returned JSON output using Java.



private String getDistanceFromDirectionsSvc(String paramOrigin, String paramDestination) throws IOException {


    URL url =
        new URL("https://maps.googleapis.com/maps/api/directions/json?" + "origin=" + URLEncoder.encode(paramOrigin,
                "UTF-8") +
            "&destination=" + URLEncoder.encode(paramDestination, "UTF-8") + "&alternatives=true" +
            "&mode=DRIVING" + "&sensor=FALSE" + "&key=xyz");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    String line, outputString = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    while ((line = reader.readLine()) != null) {
        outputString += line;
    }

    System.out.println(outputString);
    JSONParser parser = new JSONParser();

    Object obj = null;
    try {
        obj = parser.parse(outputString);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    JSONObject jsonObject = (JSONObject) obj;
    String status = (String) jsonObject.get("status");

    if (status.equals("OK")) {

        JSONArray wayPointsArray = (JSONArray) jsonObject.get("geocoded_waypoints");
        Iterator iter = (Iterator) wayPointsArray.iterator();

        String geoCoderStatus = "";
        String errorMessage = "";

        while (iter.hasNext()) {
            JSONObject wayPointObject = (JSONObject) iter.next();

            geoCoderStatus = wayPointObject.get("geocoder_status").toString();

            String partialMatch = "false";
            if (wayPointObject.containsKey("partial_match")) {
                partialMatch = wayPointObject.get("partial_match").toString();
            }

            if (!geoCoderStatus.equals("OK")) {

                errorMessage = "Invalid GeoCoder status returned = " + geoCoderStatus;
                geoCoderStatus = "FAILED";

            }

            if (partialMatch.equals("true")) {

                errorMessage = "Exact Address match not found. Please make sure Address is valid";
                geoCoderStatus = "FAILED";

            }
        }

        if (geoCoderStatus.equals("OK")) {

            JSONArray routesArray = (JSONArray) jsonObject.get("routes");
            Iterator i = (Iterator) routesArray.iterator();

            Integer shortestDistance = 0;

            while (i.hasNext()) {

                JSONObject routeObject = (JSONObject) i.next();

                JSONArray legsArray = (JSONArray) routeObject.get("legs");
                Iterator j = (Iterator) legsArray.iterator();

                while (j.hasNext()) {

                    JSONObject legsObject = (JSONObject) j.next();
                    JSONObject distanceObject = (JSONObject) legsObject.get("distance");

                    int distance = Integer.parseInt(distanceObject.get("value").toString());

                    // ++ Get the shortest of all Alternate Routes.
                    if (shortestDistance == 0 || distance < shortestDistance) {
                        shortestDistance = distance;
                    }

                }
            }

            Double distMiles = shortestDistance.doubleValue();
            distMiles = distMiles / 1609.34; //convert in miles

            DecimalFormat df = new DecimalFormat("#.##");

            return df.format(distMiles).toString();

        } else {

            OAException geoCodeException = new OAException(errorMessage);
            throw geoCodeException;
        }
    } else {

        OAException apiStatusException = new OAException("API Service Status Error = " + status);
        throw apiStatusException;

    }

}

No comments:

Post a Comment