title: Google Map API v2 - Get Driving Distance from Current Location to Known Locations
body: <p>I'm trying to figure out how to display the driving distance from the current location to four known locations. I'm not showing a map on the screen, I just need to display how many miles away the user currently is from those locations. I took an example from <a href="http://wptrafficanalyzer.in/blog/driving-distance-and-travel-time-duration-between-two-locations-in-google-map-android-api-v2/" rel="nofollow">Here</a> and modified it a little. It is bringing back the correct distance but I can't figure out how to pass in each of the 4 end locations, or differentiate between them.</p>
  
  <p>What do I need to do in order to get the distance to each of the 4 locations and display each of those distances in separate TextViews?</p>
  
  <p><strong>Update question: How do I calculate the distance for each of the 4 TextViews separately?</strong></p>
  
  <p>With the code below I'm able to do what I want for the first TextView</p>
  
  <p><strong>Java</strong></p>
  
  <pre><code>public class Locations extends Fragment {
  
  private Location currentLocation = null;
  private LocationManager locationManager;
  private GeoPoint currentPoint;
  
  TextView location1;
  
  ArrayList&lt;LatLng&gt; markerPoints;
  GoogleMap map;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  
      getLastLocation();
  }
  
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
  }
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.activity_locations, container, false);
      ...some other stuff being done here...
      // Return view
      return view;
  }
  
  public void getLastLocation(){
      String provider = getBestProvider();
      currentLocation = locationManager.getLastKnownLocation(provider);
  
      this.markerPoints = new ArrayList&lt;LatLng&gt;();
  
      LatLng fromPosition = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
      LatLng toPosition = new LatLng(29.633289, -82.305838);
      // These are the other 3 end locations
      LatLng toPosition1 = new LatLng(35.205374, -82.614587);
      LatLng toPosition2 = new LatLng(35.405342, -82.316587);
      LatLng toPosition3 = new LatLng(35.702354, -82.515837);
  
      Locations.this.markerPoints.add(fromPosition);
      Locations.this.markerPoints.add(toPosition);
  
      // Getting URL to the Google Directions API
      String url = Locations.this.getDirectionsUrl(fromPosition, toPosition);
  
      DownloadTask downloadTask = new DownloadTask();
  
      // Start downloading json data from Google Directions API
      downloadTask.execute(url);
  
      if(currentLocation != null) {
          setCurrentLocation(currentLocation);
      } else { 
          // do something
      }
  }
  
  public String getBestProvider() {
      locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
      Criteria criteria = new Criteria();
      criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
      criteria.setAccuracy(Criteria.NO_REQUIREMENT);
      String bestProvider = locationManager.getBestProvider(criteria, true);
      return bestProvider;
  }
  
  public void setCurrentLocation(Location location){
      // Get current location
      int currLatitude = (int) (location.getLatitude()*1E6);
      int currLongitude = (int) (location.getLongitude()*1E6);
      currentPoint = new GeoPoint(currLatitude,currLongitude); 
      // Set current location
      currentLocation = new Location("");
      currentLocation.setLatitude(currentPoint.getLatitudeE6() / 1e6);
      currentLocation.setLongitude(currentPoint.getLongitudeE6() / 1e6);
  }
  
  private String getDirectionsUrl(LatLng origin, LatLng dest) {
      // Origin of route
      String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
      // Destination of route
      String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
      // Sensor enabled
      String sensor = "sensor=false";
      // Building the parameters to the web service
      String parameters = str_origin + "&amp;" + str_dest + "&amp;" + sensor;
      // Output format
      String output = "json";
      // Building the url to the web service
      String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
  
      return url;
  }
  
  /** A method to download json data from url */
  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("Exception while downloading url", e.toString());
      } finally {
          iStream.close();
          urlConnection.disconnect();
      }
      return data;
  }
  
  // Fetches data from url passed
  private class DownloadTask extends AsyncTask&lt;String, Void, ArrayList&lt;String&gt;&gt; {
      @Override
      protected ArrayList&lt;String&gt; doInBackground(String... urlList) {
          try {
              ArrayList&lt;String&gt; returnList = new ArrayList&lt;String&gt;();
              for (String url : urlList) {
                  // Fetching the data from web service
                  String data = Locations.this.downloadUrl(url);
                  returnList.add(data);
              }
              return returnList;
          } catch (Exception e) {
              Log.d("Background Task", e.toString());
              return null; // Failed, return null
          }
      }
  
      // Executes in UI thread, after the execution of
      // doInBackground()
      @Override
      protected void onPostExecute(ArrayList&lt;String&gt; results) {
          super.onPostExecute(results);
  
          ParserTask parserTask = new ParserTask();
  
          for (String url : results) {
              parserTask.execute(url);
          }
  
          // Invokes the thread for parsing the JSON data
          // parserTask.execute(results);
      }
  }
  
  /** A class to parse the Google Places in JSON format */
  private class ParserTask extends AsyncTask&lt;String, Integer, ArrayList&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt;&gt; {
      // Parsing the data in non-ui thread
      @Override
      protected ArrayList&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; doInBackground(String... jsonData) {
          try {
              ArrayList&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; routes = new ArrayList&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt;();
  
              // for (String url : jsonData) {
              for (int i = 0; i &lt; jsonData.length; i++) {
                  JSONObject jObject = new JSONObject(jsonData[i]);
  
                  DirectionsJSONParser parser = new DirectionsJSONParser();
                  // Starts parsing data
                  routes = (ArrayList&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt;) parser.parse(jObject);
              }
              return routes;
          } catch (Exception e) {
              Log.d("Background task", e.toString());
              return null; // Failed, return null
          }
      }
  
      // Executes in UI thread, after the parsing process
      @Override
      protected void onPostExecute(ArrayList&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; result) {
          if (result.size() &lt; 1) {
              Toast.makeText(getActivity(), "No Points", Toast.LENGTH_LONG).show();
              return;
          }
  
          TextView tv1 = (TextView) getActivity().findViewById(R.id.location1);
          TextView tv2 = (TextView) getActivity().findViewById(R.id.location2);
          TextView tv3 = (TextView) getActivity().findViewById(R.id.location3);
          TextView tv4 = (TextView) getActivity().findViewById(R.id.location4);
  
          TextView[] views = { tv1, tv2, tv3, tv4 };
  
          // Traversing through all the routes
          for (int i = 0; i &lt; result.size(); i++) {
              // Fetching i-th route
              List&lt;HashMap&lt;String, String&gt;&gt; path = result.get(i);
              String distance = "No distance";
  
              // 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) {
                      distance = point.get("distance");
                      continue;
                  }
              }
  
              Log.d("Distance: ", distance);
  
              // Set text
              views[i].setText(distance);
          }
      }
  }
  </code></pre>
  
  <p><strong>XML</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent" &gt;
  
  &lt;LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:orientation="vertical" &gt;
      &lt;TextView
          android:id="@+id/location1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" /&gt;
      &lt;TextView
          android:id="@+id/location2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginTop="5dp"
          android:text="TextView" /&gt;
      &lt;TextView
          android:id="@+id/location3"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginTop="5dp"
          android:text="TextView" /&gt;
      &lt;TextView
          android:id="@+id/location4"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginTop="5dp"
          android:text="TextView" /&gt;
  &lt;/LinearLayout&gt;
  &lt;/RelativeLayout&gt;
  </code></pre>
  
  <p>Any help figuring this out and/or suggestions to better this code will be greatly appreciated.</p>