Android Tutorial Calculation of Distance in Km between two points on MapFragment

Hi I share a simple solution to calculate the distance in km between two points on MapFragment. I hope it will be of help to anyone who works with the GoogleMaps v2.50 library.

The coordinates used for this example are set in the image.


The code is the translation of Haversine's formula.

Sub Activity_Create(FirstTime As Boolean)
    CalcDistance(48.0193200,9.4042800,48.01932, 11.3819)

Sub CalcDistance(lat1 As Double,lon1 As Double,lat2 As Double, lon2 As Double)
    Dim R As Double=6371
    Dim dLat As Double=toRad(lat2-lat1)
    Dim dLon As Double=toRad(lon2-lon1)
    Dim alat1 As Double=toRad(lat1)
    Dim alat2 As Double=toRad(lat2)
    Dim a As Double = ASin(dLat/2)*ASin(dLat/2)+ASin(dLon/2)*ASin(dLon/2)*ACos(alat1)*ACos(alat2)
    Dim c As Double=2*ATan2(Sqrt(a),Sqrt(1-a))
    Dim d As Double=R*c
    Log("Distance: "&Round2(d,1))
    Return d
End Sub

Sub toRad(Value As Double) As Double
    Dim value2 As Double
    value2 = Value*cPI/180
    Return value2

End Sub


Active Member
Licensed User
hi emex i'm creating an app that uses the MapFragment and i tested the coordinates in an online simulator that calculates the distance between two points and matches. Perhaps there may be a small difference in decimals.


Active Member
Licensed User
I agree with emexes, your calculation seems to be wrong. Here's my code to calculate the distance in meters:
Public Sub GetSimpleDistanceInMetersBetweenTwoLatLons(lat1 As Double, lon1 As Double, lat2 As Double, lon2 As Double) As Double
    Dim Deg2Rad As Double = 2*cPI/360
    Dim R As Double = 6371e3
    Dim phi1 As Double = lat1 * Deg2Rad
    Dim phi2 As Double = lat2 * Deg2Rad
    Dim deltaphi As Double = phi2-phi1
    Dim deltalambda As Double = (lon2-lon1) * Deg2Rad
    Dim sindeltaphihalf As Double = Sin(deltaphi/2)
    Dim sindeltalambdahalf As Double = Sin(deltalambda/2)
    Dim a As Double = sindeltaphihalf * sindeltaphihalf + Cos(phi1) * Cos(phi2) * sindeltalambdahalf * sindeltalambdahalf
    Dim c As Double = 2 * ATan2(Sqrt(a), Sqrt(1-a))
    Return R*c
End Sub

Dim SimpleDistance As Double = GetSimpleDistanceInMetersBetweenTwoLatLons(48.0193200,9.4042800,48.01932, 11.3819)
'returns 147083.5 meters


Active Member
Licensed User
Actually trying again now I also notice that there is some error in the calculations I will review the solution 😅


Licensed User
I will review the solution 😅
Sounds great, because it was otherwise a useful snippet. You can just edit the post rather than rewrite it. And while you're busy removing all trace of having human fallibility, I'll do likewise with my posts. 🍻