yamcsha

Map - distance

May 21st, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. <?php
  2.  
  3. class Map
  4. {
  5.     const UNIT_MILE          = 0;
  6.     const UNIT_KILOMETER     = 1;
  7.     const UNIT_NAUTICAL_MILE = 2;
  8.  
  9.     /**
  10.      * Calculate distance between two coords positions
  11.      *
  12.      * @param float $lat1   Latitude of the first coord
  13.      * @param float $lon1   Longitude of the first coord
  14.      * @param float $lat2   Latitude of the second coord
  15.      * @param float $lon2   Longitude of the second coord
  16.      * @param int $unit     Unit of measure of the returned value
  17.      *
  18.      * @return float        Distance measured
  19.      */
  20.     public function distance($lat1, $lon1, $lat2, $lon2, $unit = self::UNIT_MILE)
  21.     {
  22.         $theta = $lon1 - $lon2;
  23.         $dist  = sin(deg2rad($lat1)) * sin(deg2rad($lat2))
  24.                + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  25.         $dist  = acos($dist);
  26.         $dist  = rad2deg($dist);
  27.         $miles = $dist * 60 * 1.1515;
  28.  
  29.         switch ($unit) {
  30.            case self::UNIT_KILOMETER:
  31.                 return ($miles * 1.609344);
  32.                 break;
  33.  
  34.             case self::UNIT_NAUTICAL_MILE:
  35.                 return ($miles * 0.8684);
  36.                 break;
  37.  
  38.             case self::UNIT_MILE:
  39.             default:
  40.                 return $miles;
  41.                 break;
  42.         }
  43.      }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment