Tuesday, 14 February 2017

Calculate Distance Between given by Latitude and Longitude in Php

<?php
                                                          
<----- Remember South latitudes are negative, east longitudes are positive.   ----->    
                                                      
<-----lati1, long1 = Latitude and Longitude of point 1 (in decimal degrees)   ----->
<-----lati2, long2 = Latitude and Longitude of point 2 (in decimal degrees)   ----->
<-----          unit = the unit you desire for results                        ----->
<-----           where: 'M' is statute miles (default)                        
                        'K' is kilometers                                     
                        'N' is nautical miles                                 ----->         

function distance($lati1, $long1, $lati2, $long2, $unit) {

  $theta = $long1 - $long2;
  $distance = sin(deg2rad($lati1)) * sin(deg2rad($lati2)) +  cos(deg2rad($lati1)) * cos(deg2rad($lati2)) * cos(deg2rad($theta));
  $distance = acos($distance);
  $distance = rad2deg($distance);
  $miles = $distance * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

echo distance(38.9697, -98.80322, 31.46786, -98.53506, "M") . " miles<br>";
echo distance(38.9697, -98.80322, 31.46786, -98.53506, "K") . " kilometers<br>";
echo distance(38.9697, -98.80322, 31.46786, -98.53506, "N") . " nautical miles<br>";

?>

0 comments:

Post a Comment