Skip to content

Instantly share code, notes, and snippets.

@cybertiwari
Created October 31, 2021 16:14
Show Gist options
  • Save cybertiwari/e0197cd6aee8386c86a4e64209bff2fe to your computer and use it in GitHub Desktop.
Save cybertiwari/e0197cd6aee8386c86a4e64209bff2fe to your computer and use it in GitHub Desktop.
Calculate distance between two latitude and longitude in php using the Great-circle distance formulae
<?php
function calculateDistance($firstLatitude, $firstLongitude, $secondLatitude,$secondLongitude)
{
//get polar angle θ (theta) (angle with respect to polar axis)
$theta = $firstLongitude - $secondLongitude;
$radians = sin(
deg2rad($firstLatitude)
) * sin(
deg2rad($secondLatitude)
) + cos(
deg2rad($firstLatitude)
) * cos(
deg2rad($secondLatitude)
) * cos(
deg2rad($theta)
);
//get the arc cosine value of given radians(distance in radians)
$distance = acos($radians);
//convert radians into miles(multiple with earth radius in miles)
$miles = $distance * 3959;
//convert miles into kilometer(1 miles = 1.60934)
$km = $miles * 1.60934;
return $km;
}
$distance = calculateDistance(20.5937,78.9629,37.0902,95.7129);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment