1

I'm making an app for tracking the driven routes via GPS, for the database I used SQLite. When the current position gets changed, the data (latitude, longitude, date) will be saved into the database, so I have a list of many coordinates+dates in my database.

Now, I want to calculate the distance for the whole route. I know the start and end position and the intermediate positions. I also know how to calculate a distance between two positions. I do NOT know how to calculate the distance for all segments. Can someone help me?

This is how I calculate the distance between two positions:

private double calculateDistance(double fromLong, double fromLat,double toLong, double toLat) {
    double d2r = Math.PI / 180;
    double dLong = (toLong - fromLong) * d2r;
    double dLat = (toLat - fromLat) * d2r;
    double a = Math.pow(Math.sin(dLat / 2.0), 2) + Math.cos(fromLat * d2r)
            * Math.cos(toLat * d2r) * Math.pow(Math.sin(dLong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 6367000 * c;
    return Math.round(d);

}
KarlP
  • 5,149
  • 2
  • 28
  • 41
Hello-World
  • 183
  • 1
  • 1
  • 10

1 Answers1

0

OK since you are struggling. This is a start:

Assuming you have a prepared statement like this:

select lat, lon from position order by save_date

You can sum the segments like this:

double total = 0.0;
double a_lat;
double a_lon;


// first lat
if( rs.next() == false) return 0.0;  // nothing in db.

a_lat = rs.getDouble("lat");
a_lon = rs.getDouble("lon");

while( rs.next()) {
   b_lat = rs.getDouble("lat");
   b_lon = rs.getDouble("lon");

   double segment = calcLength(a_lat, a_lon, b_lat, b_lon);
   if( segment < MINIMUM_SEG_LENGTH) {
       continue; // skip this point, it's too close to the previous.
   }
   total+=segmentLength;

  a_lat = b_lat; // oops, forgot this.
  a_lon = b_lon; 
}

return total;
KarlP
  • 5,149
  • 2
  • 28
  • 41
  • If the segments are short, the total length will not be very accurate due to accumulating errors. It is probably best to simply skip points if the the segment length is too small. – KarlP Jan 27 '14 at 15:18