JavaScript: Calculating the distance between two points of latitude and longitude (Haversine Formula)

From The Travis van der Font Wiki
Jump to: navigation, search
Haversine formula is the solution. Code below:
const earth_radius_km  = 6371;

// This function converts decimal degrees to radians
function deg2rad(degrees)
{
    return degrees * Math.PI / 180;
}

function st_distance_sphere(lat1, lon1, lat2, lon2)
{
    var dLat = deg2rad(lat2-lat1);
    var dLon = deg2rad(lon2-lon1);

    lat1 = deg2rad(lat1);
    lat2 = deg2rad(lat2);

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 

    return earth_radius_km  * c;
}

Examples

// The distance between same points should be 0
st_distance_sphere(0,0,0,0);

// From London to Arlington should be 5918.185064088764
st_distance_sphere(51.5, 0, 38.8, -77.1)