Calculates the distance between to geo-locations using the haversine formula - Node.js Math

Node.js examples for Math:Math Function

Description

Calculates the distance between to geo-locations using the haversine formula

Demo Code

/**/* w  w w .  ja  v a2s.  c  om*/
 * Calculates the distance between to geo-locations using the haversine formula
 * @param lat1
 * @param lon1
 * @param lat2
 * @param long2
 * @returns distance in meters between points
 */
module.exports.distanceBetweenPoints = function(lat1, lon1, lat2, lon2) {
    var R = 6371000; // m
    var dLat = (lat2-lat1).toRad();
    var dLon = (lon2-lon1).toRad();
    var lat1 = lat1.toRad();
    var lat2 = lat2.toRad();

    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));
    var d = R * c;
    return d;
};

Related Tutorials