# RPGLE calculate distance between two points - Using Latitude and Longitude

This uses the haversine formula to calculate great-circle distances between the two points – that is, the shortest distance over the earth’s surface – giving an "as-the-crow-flies" distance between the points (ignoring any hills!).

 Haversine formula: R = earth’s radius (mean radius = 6,371km) Δlat = lat2− lat1 Δlong = long2− long1 a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2) c = 2.atan2(√a, √(1−a)) d = R.c (Note that angles need to be in radians to pass to trig functions). JavaScript: ```var R = 6371; // km var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad();  ``` ```var a = Math.sin(dLat/2) * Math.sin(dLat/2) +         Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *         Math.sin(dLon/2) * Math.sin(dLon/2);  ``` `var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); ` `var d = R * c;`

RPGLE sample code (distance in miles)
```h option(*srcstmt:*nodebugio)
h BndDir('QC2LE')  DftActGrp(*NO)
*
* Prototypes
d ACosine         Pr             8f   ExtProc('acos')
d  double                        8f   Value
d Cosine          Pr             8f   ExtProc('cos')
d  double                        8f   Value
d Sine            Pr             8f   ExtProc('sin')
d  double                        8f   Value

d  \$home_lat      s             11p 6
d  \$home_lng      s             11p 6
d  \$away_lat      s             11p 6
d  \$away_lng      s             11p 6
d  \$distance      s              8p 2

d  home_lat       s             11p 6
d  home_lng       s             11p 6
d  away_lat       s             11p 6
d  away_lng       s             11p 6

*
*----- Main Routine
*

c     *entry        plist
c                   parm                    \$home_lat
c                   parm                    \$home_lng
c                   parm                    \$away_lat
c                   parm                    \$away_lng
c                   parm                    \$distance

c                   eval(h)   home_lat = \$home_lat/57.2958
c                   eval(h)   home_lng = \$home_lng/57.2958
c                   eval(h)   away_lat = \$away_lat/57.2958
c                   eval(h)   away_lng = \$away_lng/57.2958

c                   eval(h)   \$distance =
c                             ACosine((Sine(home_lat) * Sine(away_lat)) +
c                             (Cosine(away_lng - home_lng) *
c                              Cosine(home_lat) *
c                              Cosine(away_lat))) * 3963.10

c                   eval      *inlr = *on
c                   return
```