# Android QuestionGPS measure the distance between two coordinates

#### Hamied Abou Hulaikah

##### Well-Known Member
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.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?

#### Ohanian

##### Active Member
Longtime User
• Hamied Abou Hulaikah

#### Semen Matusovskiy

##### Well-Known Member
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:

Replies
6
Views
1K
Replies
3
Views
780
Replies
9
Views
3K
Replies
0
Views
882
Replies
14
Views
8K