2

I want to create an android application where the user can select the start and end point then the application will calculate the distance and time take taken to reach the destination.

in order to do that, i use the google direction web service.

Here is the sample request:

JSON data of Google Direction API

the return object is json object.

i dont know how to request to the web service and how to parse the json object.

thank you in advance.

Steve Benett
  • 12,843
  • 7
  • 59
  • 79
MAJ
  • 27
  • 1
  • 6

2 Answers2

2
//try this way
 String response = new JSONParser().getJSONFromUrl(makeURL(startLatitude,startLongitude,endLatitude,endtLongitude),new responseListener() {
        @Override
        public void onResponseComplete(String response) {
            try {
                ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
                JSONArray step = new JSONObject(response).getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
                        .getJSONObject(0).getJSONArray("steps");

                for (int i = 0; i < step.length(); i++) {
                    HashMap<String,Object> row = new HashMap<String,Object>();
                    row.put("address", step.getJSONObject(i).getString("html_instructions"));
                    row.put("start",new LatLng(Double.parseDouble(step.getJSONObject(i).getJSONObject("start_location").getString("lat")), Double.parseDouble(step.getJSONObject(i).getJSONObject("start_location").getString("lng"))));
                    row.put("end",  new LatLng(Double.parseDouble(step.getJSONObject(i).getJSONObject("start_location").getString("lat")), Double.parseDouble(step.getJSONObject(i).getJSONObject("start_location").getString("lng"))));
                    list.add(row);

                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    });
    public String makeURL(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
        StringBuilder localStringBuilder = new StringBuilder();
        localStringBuilder.append("http://maps.googleapis.com/maps/api/directions/json");
        localStringBuilder.append("?origin=");
        localStringBuilder.append(Double.toString(startLatitude));
        localStringBuilder.append(",");
        localStringBuilder.append(Double.toString(startLongitude));
        localStringBuilder.append("&destination=");
        localStringBuilder.append(Double.toString(endLatitude));
        localStringBuilder.append(",");
        localStringBuilder.append(Double.toString(endLongitude));
        localStringBuilder.append("&sensor=false&mode=driving&alternatives=true");
        return localStringBuilder.toString();
    }

    public class JSONParser {
        InputStream is = null;
        JSONObject jObj = null;
        String json = "";

        public JSONParser() {
        }

        public void getJSONFromUrl(final String url, final responseListener target) {
            new AsyncTask<Void, Void, String>() {
                protected String doInBackground(Void... params) {
                    HttpURLConnection httpURLConnection = null;
                    StringBuilder stringBuilder = new StringBuilder();
                    try {
                        httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
                        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());

                        int read;
                        char[] buff = new char[1024];
                        while ((read = inputStreamReader.read(buff)) != -1) {
                            stringBuilder.append(buff, 0, read);
                        }
                        return stringBuilder.toString();
                    } catch (MalformedURLException localMalformedURLException) {
                        return "";
                    } catch (IOException localIOException) {
                        return "";
                    } finally {
                        if (httpURLConnection != null)
                            httpURLConnection.disconnect();
                    }
                }

                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    target.onResponseComplete(result);
                }
            }.execute();
        }
    }

    interface responseListener{
        public void onResponseComplete(String response);
    }
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
  • dear haresh, can u explain how i can implement those code into my apps. what i mean is that, is that the code i should write inside the oncreate method or what ? – MAJ Oct 29 '13 at 14:21
  • the other thing that bothering me is, what is the value hold by the String response variable ? – MAJ Oct 29 '13 at 14:23
0

You can follow this way :

Better Explanation of JSON Parsing...

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
  • how about make the HTTPRequest itself? in the coding sample, there is no example on how to make the HTTPRequest to the google site. – MAJ Oct 29 '13 at 08:37