Friday, April 12, 2013

Get Distance Between Two Lat Long

Create function to calculate distance. and pass lat long of first place and second place. and one parameter for the distance type.

function calculateDistance($lat1,$lng1,$lat2,$lng2,$miles = true)
{
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;

    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;
 
    return ($miles ? ($km * 0.621371192) : $km);
}

Function Call:

$data['d_dist'] = calculateDistance((double)($cur_lat),(double)($cur_lon),(double)($lat2),(double)($lon2),false);

Pass false to get distance in km.


Option 2(sort function):

function calculateDistance($lat1, $lng1, $lat2, $lon2) {
$distance = (3958*3.1415926*sqrt(($lat2-$lat1)*($lat2-$lat1) + cos($lat2/57.29578)*cos($lat1/57.29578)*($lon2-$lng1)*($lon2-$lng1))/180);
return $distance; // Distance calculated in miles
}


No comments:

Post a Comment