title: Calculate the distance between two positions Android Studio
body: <p>I'm building an application that tracks my running and walking but I'm getting some trouble with calculating the total distance. </p>
  
  <p>Here is a part of my code where I'm getting the values of latitude and longitude and where I do my calculation of the distance.</p>
  
  <pre><code>public class SportsActicity {
  
  protected Integer userId;
  protected ArrayList&lt;Position&gt; route = new ArrayList&lt;Position&gt;();
  
  public SportsActicity() {
      this.userId = 1;
  }
  
  public void track(Double latitude, Double longitude, Double altitude, float speed, long chron) {
      Date currentDate = new Date();
      Position currentPosition = new Position(currentDate, latitude, longitude, altitude, speed, chron);
      route.add(currentPosition);
      // Float velocidade =  (locat.getSpeed()*3600)/1000;
  }
  
  public double getTotalDistance() {
      double distance = 0;
      if(route.size() &gt; 1) {
          for (Integer i = 0; i &lt; route.size() - 1; i++) {
              distance += test(route.get(i).latitude, route.get(i).longitude, route.get(i + 1).latitude, route.get(i + 1).longitude);
          }
      }
      return distance;
  }
  
  public Float test(Double lat1, Double lon1, Double lat2, Double lon2) {
      double earthRadius = 6371;
      double latDiff = Math.toRadians(lat2-lat1);
      double lngDiff = Math.toRadians(lon2-lon1);
      double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +           
                 Math.cos(Math.toRadians(lat1))* 
                 Math.cos(Math.toRadians(lat2))* Math.sin(lngDiff /2) * 
                 Math.sin(lngDiff /2); 
      double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      double distance = earthRadius * c;
  
      int meterConversion = 1609;
  
      return new Float(distance * meterConversion).floatValue();
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/ssjIY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ssjIY.png" alt="enter image description here"></a></p>
  
  <p>If I'm not moving, the total distance is always incrementing, around 10 (no idea if it is in meters), and the values I'm getting don't look correct. </p>