0

I am developing an Android 10 application on Java, in which I have to calculate the distance between two locations, but I've faced an issue.

The output is supposed to be as a set of distances between the points from the database. The coordinates are stored in SQLite database as a set of latitudes and longitudes. The getPoints method works well and returns list of locations correctly. I have implemented the methods of converting degrees to radians and vice versa and converting distance in degrees into miles. To this point everything works without obstacles.

The issue occurs on calculating the distance. I decided to use the Haversine formula because the input data is in suitable format for it. However, the total distance is always wrong, sometimes it's even negative integer, which is inappropriate.

Here is the code.

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);
}
  • Have you tried putting a few println statements to check if your intermediate calculations are what you expect? – NomadMaker Dec 25 '19 at 13:56
  • Where are those formulas from? [Wikipedia](https://en.wikipedia.org/wiki/Haversine_formula) shows quite different ones. What are those `60` and `1.1515`? – Nico Schertler Dec 25 '19 at 18:04

0 Answers0