Skip to content

Instantly share code, notes, and snippets.

@peteeveleigh
Created July 5, 2017 20:51
Show Gist options
  • Save peteeveleigh/e1aa9c5a19e77d4d644cfaca92614725 to your computer and use it in GitHub Desktop.
Save peteeveleigh/e1aa9c5a19e77d4d644cfaca92614725 to your computer and use it in GitHub Desktop.
PHP function to determine whether or not 2 lat/lon points are within a specified distance of each other (Great Circle)
<?php
$pointA = array(
'lat' => 51.863119,
'lon' => -2.21064
);
$pointB = array(
'lat' => 51.957807,
'lon' => -2.640603
);
$radius = 10;
if(withinRadius($pointA,$pointB,$radius))
{
echo("within ".$radius);
} else {
echo("not within ".$radius);
}
function withinRadius($pointA, $pointB, $within)
{
$earthR = 6371000; // radius of earth
// convert to radians
$latA = deg2rad($pointA['lat']);
$lonA = deg2rad($pointA['lon']);
$latB = deg2rad($pointB['lat']);
$lonB = deg2rad($pointB['lon']);
// get difference between lat/lon radians
$deltaLat = $latA - $latB;
$deltaLon = $lonA - $lonB;
$distance = 2 * asin(sqrt(pow(sin($deltaLat / 2), 2) +
cos($latA) * cos($latB) * pow(sin($deltaLon / 2), 2))) * $earthR;
return $distance <= $within ? TRUE : FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment