title: Calculating Total Distance Between Way Points android google api
body: <p>I have develop an application which draws the route between start point and the destination and also user will be able to mark some waypoints along that path and the route will be drawn correctly. But I can only get the distance when I only mark 2 places on the map. If I mark 2, 3 places it will not give me the distance. These are my codes,</p>
  
  <pre><code>public class DirectionsJSONParser {
  
  /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
  public List&lt;List&lt;HashMap&lt;String,String&gt;&gt;&gt; parse(JSONObject jObject){
  
      List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; routes = new ArrayList&lt;List&lt;HashMap&lt;String,String&gt;&gt;&gt;();
      JSONArray jRoutes = null;
      JSONArray jLegs = null;
      JSONArray jSteps = null;
      JSONObject jDistance = null;
      JSONObject jDuration = null;
  
      try {
  
          jRoutes = jObject.getJSONArray("routes");
  
          /** Traversing all routes */
          for(int i=0;i&lt;jRoutes.length();i++){
              jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
              List path = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
  
              /** Traversing all legs */
              for(int j=0;j&lt;jLegs.length();j++){
                  /** Getting distance from the json data */
                  jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                  HashMap&lt;String, String&gt; hmDistance = new HashMap&lt;String, String&gt;();
                  hmDistance.put("distance", jDistance.getString("text"));
  
                  /** Getting duration from the json data */
                  jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                  HashMap&lt;String, String&gt; hmDuration = new HashMap&lt;String, String&gt;();
                  hmDuration.put("duration", jDuration.getString("text"));
  
                  /** Adding distance object to the path */
                  path.add(hmDistance);
  
                  /** Adding duration object to the path */
                  path.add(hmDuration);
                  jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
  
                  /** Traversing all steps */
                  for(int k=0;k&lt;jSteps.length();k++){
                      String polyline = "";
                      polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                      List&lt;LatLng&gt; list = decodePoly(polyline);
  
                      /** Traversing all points */
                      for(int l=0;l&lt;list.size();l++){
                          HashMap&lt;String, String&gt; hm = new HashMap&lt;String, String&gt;();
                          hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                          hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                          path.add(hm);
                      }
                  }
                  routes.add(path);
              }
          }
  
      } catch (JSONException e) {
          e.printStackTrace();
      }catch (Exception e){
      }
  
  
      return routes;
  }
  
  
  /**
   * Method to decode polyline points
   * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
   * */
  private List&lt;LatLng&gt; decodePoly(String encoded) {
  
      List&lt;LatLng&gt; poly = new ArrayList&lt;LatLng&gt;();
      int index = 0, len = encoded.length();
      int lat = 0, lng = 0;
  
      while (index &lt; len) {
          int b, shift = 0, result = 0;
          do {
              b = encoded.charAt(index++) - 63;
              result |= (b &amp; 0x1f) &lt;&lt; shift;
              shift += 5;
          } while (b &gt;= 0x20);
          int dlat = ((result &amp; 1) != 0 ? ~(result &gt;&gt; 1) : (result &gt;&gt; 1));
          lat += dlat;
  
          shift = 0;
          result = 0;
          do {
              b = encoded.charAt(index++) - 63;
              result |= (b &amp; 0x1f) &lt;&lt; shift;
              shift += 5;
          } while (b &gt;= 0x20);
          int dlng = ((result &amp; 1) != 0 ? ~(result &gt;&gt; 1) : (result &gt;&gt; 1));
          lng += dlng;
  
          LatLng p = new LatLng((((double) lat / 1E5)),
                  (((double) lng / 1E5)));
          poly.add(p);
      }
  
      return poly;
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code> private String downloadUrl(String strUrl) throws IOException {
      String data = "";
      InputStream iStream = null;
      HttpURLConnection urlConnection = null;
      try{
          URL url = new URL(strUrl);
  
          // Creating an http connection to communicate with url
          urlConnection = (HttpURLConnection) url.openConnection();
  
          // Connecting to url
          urlConnection.connect();
  
          // Reading data from url
          iStream = urlConnection.getInputStream();
  
          BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  
          StringBuffer sb  = new StringBuffer();
  
          String line = "";
          while( ( line = br.readLine())  != null){
              sb.append(line);
          }
  
          data = sb.toString();
  
          br.close();
  
      }catch(Exception e){
          Log.d("Error downloading url", e.toString());
      }finally{
          iStream.close();
          urlConnection.disconnect();
      }
      return data;
  }
  
  
  
  // Fetches data from url passed
  private class DownloadTask extends AsyncTask&lt;String, Void, String&gt; {
  
      // Downloading data in non-ui thread
      @Override
      protected String doInBackground(String... url) {
  
          // For storing data from web service
          String data = "";
  
          try{
              // Fetching the data from web service
              data = downloadUrl(url[0]);
          }catch(Exception e){
              Log.d("Background Task",e.toString());
          }
          return data;
      }
  
      // Executes in UI thread, after the execution of
      // doInBackground()
      @Override
      protected void onPostExecute(String result) {
          super.onPostExecute(result);
  
          ParserTask parserTask = new ParserTask();
  
          // Invokes the thread for parsing the JSON data
          parserTask.execute(result);
  
      }
  }
  
  /** A class to parse the Google Places in JSON format */
  private class ParserTask extends AsyncTask&lt;String, Integer, List&lt;List&lt;HashMap&lt;String,String&gt;&gt;&gt; &gt;{
  
      // Parsing the data in non-ui thread
      @Override
      protected List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; doInBackground(String... jsonData) {
  
          JSONObject jObject;
          List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; routes = null;
  
          try{
              jObject = new JSONObject(jsonData[0]);
              DirectionsJSONParser parser = new DirectionsJSONParser();
  
              // Starts parsing data
              routes = parser.parse(jObject);
          }catch(Exception e){
              e.printStackTrace();
          }
          return routes;
      }
  
      // Executes in UI thread, after the parsing process
      @Override
      protected void onPostExecute(List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; result) {
          ArrayList&lt;LatLng&gt; points = null;
          PolylineOptions lineOptions = null;
          MarkerOptions markerOptions = new MarkerOptions();
          String distance = "";
          String duration = "";
  
          if(result.size()&lt;1){
              Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
              return;
          }
  
          // Traversing through all the routes
          for(int i=0;i&lt;result.size();i++){
              points = new ArrayList&lt;LatLng&gt;();
              lineOptions = new PolylineOptions();
  
              // Fetching i-th route
              List&lt;HashMap&lt;String, String&gt;&gt; path = result.get(i);
  
              // Fetching all the points in i-th route
              for(int j=0;j&lt;path.size();j++){
                  HashMap&lt;String,String&gt; point = path.get(j);
  
                  if(j==0){    // Get distance from the list
                      distance = (String)point.get("distance");
                      continue;
                  }else if(j==1){ // Get duration from the list
                      duration = (String)point.get("duration");
                      continue;
                  }
  
                  double lat = Double.parseDouble(point.get("lat"));
                  double lng = Double.parseDouble(point.get("lng"));
                  LatLng position = new LatLng(lat, lng);
  
                  points.add(position);
              }
  
              // Adding all the points in the route to LineOptions
              lineOptions.addAll(points);
              lineOptions.width(2);
              lineOptions.color(Color.RED);
          }
  
          tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
  
          // Drawing polyline in the Google Map for the i-th route
          map.addPolyline(lineOptions);
      }
  
  }
  </code></pre>
  
  <blockquote>
    <p>URL I used to request</p>
  </blockquote>
  
  <pre><code> String parameters = str_origin+"&amp;"+str_dest+"&amp;"+sensor+"&amp;"+waypoints;
  
      // Output format
      String output = "json";
  
      // Building the url to the web service
      String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/0E7FK.png" rel="nofollow noreferrer">Error I found when I used 4 points with 2 way points</a></p>
  
  <p>This is in onPostExecute method on lines,</p>
  
  <pre><code> double lat = Double.parseDouble(point.get("lat"));
   double lng = Double.parseDouble(point.get("lng"));
   LatLng position = new LatLng(lat, lng);
  </code></pre>
  
  <p>What I have done wrong here?</p>