Skip to content

Commit

Permalink
Added a math utility class to do distance and direction calculations …
Browse files Browse the repository at this point in the history
…between two lat lon coordinates
  • Loading branch information
Thombrix committed Nov 25, 2023
1 parent 8f12962 commit ef94ddb
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions backend-laravel/app/Utility/Math.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Utility;

class Math
{
public static $earthRadius = 6371;

public static function distance($lat1, $lon1, $lat2, $lon2)
{
$lat1 = deg2rad($lat1);
$lon1 = deg2rad($lon1);
$lat2 = deg2rad($lat2);
$lon2 = deg2rad($lon2);

$latDiff = $lat2 - $lat1;
$lonDiff = $lon2 - $lon1;

$a = sin($latDiff / 2) ** 2 + cos($lat1) * cos($lat2) * sin($lonDiff / 2) ** 2;
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));

$distance = self::$earthRadius * $c;

return $distance;
}

public static function direction($lat1, $lon1, $lat2, $lon2)
{
$lat1 = deg2rad($lat1);
$lon1 = deg2rad($lon1);
$lat2 = deg2rad($lat2);
$lon2 = deg2rad($lon2);

$lonDiff = $lon2 - $lon1;

$y = sin($lonDiff) * cos($lat2);
$x = cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($lonDiff);

$bearing = atan2($y, $x);
$bearing = rad2deg($bearing);

$bearing = ($bearing + 360) % 360;

return $bearing;
}
}

0 comments on commit ef94ddb

Please sign in to comment.