Skip to content

Instantly share code, notes, and snippets.

@KminekMatej
Last active July 19, 2022 13:09
Show Gist options
  • Save KminekMatej/6f47345d70f8e77b6a7b8a7b21d8b060 to your computer and use it in GitHub Desktop.
Save KminekMatej/6f47345d70f8e77b6a7b8a7b21d8b060 to your computer and use it in GitHub Desktop.
const EARTH_RADIUS = 6371000;
/**
* Calculates the great-circle distance between two points, with
* the Haversine formula.
*
* @param float $latitudeFrom Latitude of start point in [deg decimal]
* @param float $longitudeFrom Longitude of start point in [deg decimal]
* @param float $latitudeTo Latitude of target point in [deg decimal]
* @param float $longitudeTo Longitude of target point in [deg decimal]
* @return float Distance between points in [m] (same as earthRadius)
*/
public function calculateDistance(float $latitudeFrom, float $longitudeFrom, float $latitudeTo, float $longitudeTo) {
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * self::EARTH_RADIUS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment