Android Question GPS measure the distance between two coordinates

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
Hi,
I'm using gps library generated coordinates, i want to measure the distance between two coordinates.
I googled & found this Java function.
How can i call this from b4a ?
B4X:
#if JAVA
public static double distance(double lat1, double lat2, double lon1, double lon2, double el1, double el2) {

    final int R = 6371; // Radius of the earth

    double latDistance = Math.toRadians(lat2 - lat1);
    double lonDistance = Math.toRadians(lon2 - lon1);
    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
            * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = R * c * 1000; // convert to meters

    double height = el1 - el2;

    distance = Math.pow(distance, 2) + Math.pow(height, 2);

    return Math.sqrt(distance);
}
#End If
Also What is the values of el1 & el2 means? & How i obtain them from gps library?
 

Semen Matusovskiy

Well-Known Member
Licensed User
Android's DistanceTo is enough accurate and uses more complex formulas than Haversine.

But sometimes is neccessary to synchronize calculations, for example, with own webserver. And for this purpose Haversine formula is good, because it's very simple.

In B4A Haversine formula looks so
B4X:
Sub Activity_subHaversineCalculateDistance (Latitude1 As Double, Longitude1 As Double, Latitude2 As Double, Longitude2 As Double) As Double

    Return 2 * 6371000 * ASin (Sqrt (SinD ((Latitude2 - Latitude1) * 0.5) * SinD ((Latitude2 - Latitude1) * 0.5) + CosD (Latitude1) * CosD (Latitude2) * SinD ((Longitude2 - Longitude1) * 0.5) * SinD ((Longitude2 - Longitude1) * 0.5)))

End Sub

But this formula is not very accurate (+/- 0,5%) due to using average radius of earth 6371 km.
Better to correct this value using average latitude. R varies from 6356.752 km at the poles to 6378.137 km at the equator.
In this case an error will be less than 1 m per 1 km.
 
Last edited:
Upvote 0
Top