JS: Calculate Distance Between Two Coordinates


This routine calculates the distance between two points (given the latitude/longitude of those points). It is being used to calculate the distance between two locations:

function distance(point1, point2)
{
    var EarthRadiusMeters = 6378137.0;
    var dLat = (point2[0] - point1[0]) * Math.PI / 180;
    var dLon = (point2[1] - point1[1]) * Math.PI / 180;
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(point1[0] * Math.PI / 180) * Math.cos(point2[0] * Math.PI / 180) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return EarthRadiusMeters * c;
}

Example:

distance([32.9697, -96.80322],[29.46786, -98.53506])

Result:
423232.8593012345

Note: Result as meters

Ellipsoidal parameters:

Name           Major axis, a (km)    Flattening (f)
WGS84          6378.13700	   1/298.257223563
GRS80/NAD83    6378.13700	   1/298.257222101
WGS66          6378.145            1/298.25
GRS67/IAU68    6378.16000          1/298.2472
WGS72          6378.135            1/298.26
Krasovsky      6378.245            1/298.3
Clarke66/NAD27 6378.2064           1/294.9786982138

Image copyright: movable-type.co.uk

Leave a Reply