Skip to content

Instantly share code, notes, and snippets.

@gosman
Created January 16, 2016 10:55
Show Gist options
  • Save gosman/26116b3a26c8d939330c to your computer and use it in GitHub Desktop.
Save gosman/26116b3a26c8d939330c to your computer and use it in GitHub Desktop.
PHP Get Center Point from an array of Longitude, Latitudes
<?php
$coords[]=array('lat' => '53.344104','lng'=>'-6.2674937');
$coords[]=array('lat' => '51.5081289','lng'=>'-0.128005');
print_r(get_center($coords));
function get_center($coords)
{
$count_coords = count($coords);
$xcos=0.0;
$ycos=0.0;
$zsin=0.0;
foreach ($coords as $lnglat)
{
$lat = $lnglat['lat'] * pi() / 180;
$lon = $lnglat['lng'] * pi() / 180;
$acos = cos($lat) * cos($lon);
$bcos = cos($lat) * sin($lon);
$csin = sin($lat);
$xcos += $acos;
$ycos += $bcos;
$zsin += $csin;
}
$xcos /= $count_coords;
$ycos /= $count_coords;
$zsin /= $count_coords;
$lon = atan2($ycos, $xcos);
$sqrt = sqrt($xcos * $xcos + $ycos * $ycos);
$lat = atan2($zsin, $sqrt);
return array($lat * 180 / pi(), $lon * 180 / pi());
}
?>
@gosman
Copy link
Author

gosman commented Jan 16, 2016

Our hotel suppliers for www.discounthotels.co.uk often provide data that is incorrect. I created this script to calculate the center point for a grouping of hotels so we can provide more accurate data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment