DISCLAIMER This is a hometask. Please, don't take it serious or think about this problem for more than 2 seconds. It's just not worth it. I'm sorry.
I am trying to calculate the approximate distance of the route. In the getPoints method I am requesting all the route points from the database and writing them into the array. This part works well and as expected. Here you can see the code snippet:
public ArrayList<Double> getPoints() {
ArrayList<Double> location = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select latitude,longitude from " + Table_Name_Location, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
Double latitude = cursor.getDouble(cursor.getColumnIndex("Lat"));
Double longitude = cursor.getDouble(cursor.getColumnIndex("Longi"));
location.add(latitude);
location.add(longitude);
}
}
cursor.close();
return location;
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1))
* Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
However, when the time comes to the calculating the distance itself the problem occurs. For some reason the Haversine formula calculates the distances incorrectly. I recon, that the problem somewhere in the distance method, but cannot identify it myself. I've compared my implementation of Haversine formula, but haven’t found any differences with the original one.
The Android SDK includes a Location class, which computes the Haversine formula.
Here is the source code.
The method is titled, "distanceBetween", and utilizes a private "computeDistanceAndBearing" method.
And, the computed values are, distance in meters, initial bearing, and final bearing.
Here is a ported version.
I've removed the BearingDistanceCache argument, and adjusted it to return a double array.
Here is an example usage.
According to a few sources, the distance from New York City to Los Angeles is approximately, 3,934 km.
Output