Last Updated: February 25, 2016
·
7.255K
· neeph

Calculate distance between two coordinates in PHP, JavaScript and MySQL

All returns the distance in kilometers, assuming a earth radius of 6371 km.

PHP

function calculateDistance($ini, $fin) {
    $R = 6371; // km
    $dLat = deg2rad($fin[0]-$ini[0]);
    $dLon = deg2rad($fin[1]-$ini[1]);
    $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($ini[0])) * cos(deg2rad($fin[0])) * sin($dLon/2) * sin($dLon/2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $d = $R * $c;
    return $d;
}

JavaScript

var calculateDistance = function(lat1, lon1, lat2, lon2) {
    var R = 6371; // km
    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;
}

MySQL

CREATE FUNCTION `calc_distance` (lat1 DECIMAL(10,6), long1 DECIMAL(10,6), lat2 DECIMAL(10,6), long2 DECIMAL(10,6))
RETURNS DECIMAL(10,6)
RETURN (6353 * 2 * ASIN(SQRT( POWER(SIN((lat1 - abs(lat2)) * pi()/180 / 2),2) + COS(lat1 * pi()/180 ) * COS( abs(lat2) *  pi()/180) * POWER(SIN((long1 - long2) *  pi()/180 / 2), 2) )))