'Center point of multiple gps coordinates with php

A simple php array with all coordinates

$gps = array(
    array("lat" => 62.986049, "lng" => 176.075001),
    array("lat" => 57.125353, "lng" => -165.116405)
);

I need to calculate the middle point between this two (or more) points.

In this case is somewhere near 59.34, -174.78



Solution 1:[1]

Here's my solution in PHP:

<?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));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bruno Leveque