MauroBaptista.com

Calculating Average Coordinates

PHP Laravel Coordinates

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:

1class Coordinates {
2 public function __construct(private float $latitude, private float $longitude)
3 {}
4 
5 public function getLat(): float
6 {
7 return $this->latitude;
8 }
9 
10 public function getLat(): float
11 {
12 return $this->longitude;
13 }
14}

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

1public static function average(Collection $coordinates): array
2{
3 $coordinates = $slots->map(function ($coordinates) {
4 $latitude = $coordinates->getLat();
5 $longitude = $coordinates->getLng();
6 
7 return [
8 'zeta' => sin(pi() * $longitude / 180),
9 'xi' => cos(pi() * $longitude / 180),
10 'latitude' => $latitude,
11 ];
12 });
13 
14 $zeta = $coordinates->average('zeta');
15 $xi = $coordinates->average('xi');
16 
17 $latitude = $coordinates->average('latitude');
18 $longitude = 180 * atan2($zeta, $xi) / pi();
19 
20 return new Coordinates($latitude, $longitude);
21}