Last active
July 23, 2021 12:33
-
-
Save danlapteacru/e0ee7fb2ffa612ea898454d129f5ff4c to your computer and use it in GitHub Desktop.
Calculate the center point of multiple latitude/longitude coordinates array
This file contains 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 | |
/** | |
* 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