Created
March 1, 2020 13:47
-
-
Save AidasK/17311a6a32950954335144e8977bf8cd to your computer and use it in GitHub Desktop.
PHP coords calculation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Coordinates | |
{ | |
/** | |
* @param array $c1 Expected [lat, lon] EPSG:4326 | |
* @param array $c2 Expected [lat, lon] EPSG:4326 | |
* @return float|int distance in meters | |
*/ | |
public function calculateDistance($c1, $c2) | |
{ | |
$radius = 6371000; | |
[$lat1, $lon1] = $c1; | |
[$lat2, $lon2] = $c2; | |
$dLon = deg2rad($lon2 - $lon1); | |
$lat1 = deg2rad($lat1); | |
$lat2 = deg2rad($lat2); | |
return acos( | |
sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($dLon) | |
) * $radius; | |
} | |
/** | |
* @param array $coord Expected [lat, lon] EPSG:4326 | |
* @param float $bearing Bearing in degrees | |
* @param float $distance Distance in meters | |
* @return array [lat, lon] coordinate. | |
*/ | |
function createCoord($coord, $bearing, $distance) | |
{ | |
$radius = 6371000; | |
$δ = $distance / $radius;// angular distance in radians | |
$θ = deg2rad($bearing); | |
$φ1 = deg2rad($coord[0]); | |
$λ1 = deg2rad($coord[1]); | |
$φ2 = asin(sin($φ1) * cos($δ) + | |
cos($φ1) * sin($δ) * cos($θ)); | |
$λ2 = $λ1 + atan2(sin($θ) * sin($δ) * cos($φ1), | |
cos($δ) - sin($φ1) * sin($φ2)); | |
// normalise to -180..+180° | |
$λ2 = fmod(($λ2 + 3 * pi()), (2 * pi())) - pi(); | |
return [rad2deg($φ2), rad2deg($λ2)]; | |
} | |
/** | |
* @param array $start Expected [lat, lon] EPSG:4326 | |
* @param array $end Expected [lat, lon] EPSG:4326 | |
* @return int Bearing in degrees. | |
*/ | |
function getBearing($start, $end) | |
{ | |
$startLat = deg2rad($start[0]); | |
$startLong = deg2rad($start[1]); | |
$endLat = deg2rad($end[0]); | |
$endLong = deg2rad($end[1]); | |
$dLong = $endLong - $startLong; | |
$dPhi = log(tan($endLat / 2.0 + pi() / 4.0) / | |
tan($startLat / 2.0 + pi() / 4.0)); | |
if (abs($dLong) > pi()) { | |
$dLong = ($dLong > 0.0) ? -(2.0 * pi() - $dLong) : (2.0 * pi() + $dLong); | |
} | |
return (rad2deg(atan2($dLong, $dPhi)) + 360.0) % 360.0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment