Center point of multiple gps coordinates with php



PHP Snippet 1:

<?php

function getCenterLatLng($coordinates)
{
    $x = $y = $z = 0;
    $n = count($coordinates);
    foreach ($coordinates as $point)
    {
        $lt = $point[0] * pi() / 180;
        $lg = $point[1] * pi() / 180;
        $x += cos($lt) * cos($lg);
        $y += cos($lt) * sin($lg);
        $z += sin($lt);
    }
    $x /= $n;
    $y /= $n;

    return [atan2(($z / $n), sqrt($x * $x + $y * $y)) * 180 / pi(), atan2($y, $x) * 180 / pi()];
}

/* 
** [[lat, lng], [lat, lng], ...]
** Example with Lat/Lng of US Zip codes in San Francisco, CA:
** 94102, 94103, 94104, 94105, 94107, 94108, 94109
*/
$coordinates = [
    [37.7797, -122.41924],
    [37.77323, -122.41114],
    [37.79146, -122.40207],
    [37.78978, -122.39387],
    [37.76643, -122.39461],
    [37.79203, -122.40864],
    [37.7952, -122.4222]
];

print_r(getCenterLatLng($coordinates));