Last active
March 27, 2025 13:13
-
-
Save pastranastevenaz/b1ca24e554d8f503278bfdaa26b2567b to your computer and use it in GitHub Desktop.
haversine formula in PHP
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
<?php | |
$radiusOfEarth = 3959; //miles | |
// Address 1 | |
$latitudeOne = deg2rad(33.4151843); | |
$longitudeOne = deg2rad(-111.8314724); | |
// Address 2 | |
$latitudeTwo = deg2rad(33.0581063); | |
$longitudeTwo = deg2rad(-112.0476423); | |
$distanceLongitude = $longitudeTwo - $longitudeOne; | |
$distanceLatitude = $latitudeTwo - $latitudeOne; | |
// This is the Haversine Formula expressed Mathematically | |
// a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2) | |
// c = 2 ⋅ atan2( √a, √(1−a) ) | |
// d = R ⋅ c | |
// This is the haversine Formula expressed in PHP | |
$a = sin($distanceLatitude/2) * sin($distanceLatitude/2) + cos($latitudeOne) * cos($latitudeTwo) * sin($distanceLongitude/2) * sin($distanceLongitude/2); | |
$c = 2 * asin(sqrt($a)); | |
$distance = $radiusOfEarth * $c; | |
// This is the output of all the variable assignments, steps, and final calculation | |
echo "Radius of the Earth in miles: ".$radiusOfEarth." Miles"; | |
echo "<br>"; | |
echo "Latitude One in Radians: ".$latitudeOne; | |
echo "<br>"; | |
echo "Longittude One in Radians: ".$longitudeOne; | |
echo "<br>"; | |
echo "LatitudeTwo in Radians: ".$latitudeTwo; | |
echo "<br>"; | |
echo "LongitudeTwo in Radians:".$longitudeTwo; | |
echo "<br>"; | |
echo "DistanceLongitude Variable: ".$distanceLongitude; | |
echo "<br>"; | |
echo "DistanceLatitude Variable: ".$distanceLatitude; | |
echo "<br>"; | |
echo "a variable: ".$a; | |
echo "<br>"; | |
echo "c variable: ".$c; | |
echo "<br>"; | |
echo "Distance between Sedi and Steven is: ".$distance." miles"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment