Skip to content

Instantly share code, notes, and snippets.

@danlapteacru
Last active July 23, 2021 12:33
Show Gist options
  • Save danlapteacru/e0ee7fb2ffa612ea898454d129f5ff4c to your computer and use it in GitHub Desktop.
Save danlapteacru/e0ee7fb2ffa612ea898454d129f5ff4c to your computer and use it in GitHub Desktop.
Calculate the center point of multiple latitude/longitude coordinates array
<?php
/**
* Get Lat/Lng center from an coords array
*
* @param array $coords
* @return float[]|int[]
*/
function getLatLngCenter(array $coords): array
{
$num_coords = count($coords);
$x = 0.0;
$y = 0.0;
$z = 0.0;
foreach ($coords as $coord) {
$lat = $coord[0] * pi() / 180;
$lng = $coord[1] * pi() / 180;
$a = cos($lat) * cos($lng);
$b = cos($lat) * sin($lng);
$c = sin($lat);
$x += $a;
$y += $b;
$z += $c;
}
$x /= $num_coords;
$y /= $num_coords;
$z /= $num_coords;
$lng = atan2($y, $x);
$hyp = sqrt($x * $x + $y * $y);
$lat = atan2($z, $hyp);
return [
$lat * 180 / pi(),
$lng * 180 / pi(),
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment