MauroBaptista.com

# Calculating Average Coordinates

July 01, 2021

The logic below was taken from the site: https://carto.com/blog/center-of-points/

Where the `\$coordinates` argument is a collection of `Coordinates` objects. This `Coordinates` class, should be something like:

``````    class Coordinates {
public function __construct(private float \$latitude, private float \$longitude)
{}

public function getLat(): float
{
return \$this->latitude;
}

public function getLat(): float
{
return \$this->longitude;
}
}``````

With this set, you can send this data to the method below to get the center of the coordinates in the collection.

``````    public static function average(Collection \$coordinates): array
{
\$coordinates = \$slots->map(function (\$coordinates) {
\$latitude = \$coordinates->getLat();
\$longitude = \$coordinates->getLng();

return [
'zeta' => sin(pi() * \$longitude / 180),
'xi' => cos(pi() * \$longitude / 180),
'latitude' => \$latitude,
];
});

\$zeta = \$coordinates->average('zeta');
\$xi = \$coordinates->average('xi');

\$latitude = \$coordinates->average('latitude');
\$longitude = 180 * atan2(\$zeta, \$xi) / pi();

return new Coordinates(\$latitude, \$longitude);
}`````` # Mauro Baptista

Building stuff with code and having fun in the way