With these two functions, you can calculate the distance between two latitude and longitude decimal coordinates as well as the bearing in degrees.
1function distance($lat1, $lon1, $lat2, $lon2, $unit = 'M') { 2 $theta = $lon1 - $lon2; 3 $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 4 $dist = acos($dist); 5 $dist = rad2deg($dist); 6 $dist = $dist * 60 * 1.1515; 7 8 if ($unit == "K") { 9 $dist *= 1.609344;10 } else if ($unit == "N") {11 $dist *= 0.8684;12 }1314 return round($dist, 1);15}1617function bearing($lat1, $lon1, $lat2, $lon2) {18 if (round($lon1, 1) == round($lon2, 1)) {19 if ($lat1 < $lat2) {20 $bearing = 0;21 } else {22 $bearing = 180;23 }24 } else {25 $dist = distance($lat1, $lon1, $lat2, $lon2, 'N');26 $arad = acos((sin(deg2rad($lat2)) - sin(deg2rad($lat1)) * cos(deg2rad($dist / 60))) / (sin(deg2rad($dist / 60)) * cos(deg2rad($lat1))));27 $bearing = $arad * 180 / pi();28 if (sin(deg2rad($lon2 - $lon1)) < 0) {29 $bearing = 360 - $bearing;30 }31 }3233 $dirs = array("N","E","S","W");3435 $rounded = int_round($bearing / 22.5) % 16;36 if (($rounded % 4) == 0) {37 $dir = $dirs[$rounded / 4];38 } else {39 $dir = $dirs[2 * floor(((floor($rounded / 4) + 1) % 4) / 2)];40 $dir .= $dirs[1 + 2 * floor($rounded / 8)];41 #if ($rounded % 2 == 1)42 # $dir = $dirs[round_to_int($rounded/4) % 4] . "-" . $dir;43 }4445 return $dir;46 #return $bearing;47}