You are here

protected static function GeolocationGeometryBase::getCenterFromCoordinates in Geolocation Field 8.3

Get a center latitude,longitude from an array of like geopoints.

For Example: $data = array ( 0 = > array(45.849382, 76.322333), 1 = > array(45.843543, 75.324143), 2 = > array(45.765744, 76.543223), 3 = > array(45.784234, 74.542335) );

Parameters

array $coordinates: Coordinates.

1 call to GeolocationGeometryBase::getCenterFromCoordinates()
GeolocationGeometryPolygon::generateSampleValue in modules/geolocation_geometry/src/Plugin/Field/FieldType/GeolocationGeometryPolygon.php
Generates placeholder field values.

File

modules/geolocation_geometry/src/Plugin/Field/FieldType/GeolocationGeometryBase.php, line 206

Class

GeolocationGeometryBase
Class Geolocation Geometry Base.

Namespace

Drupal\geolocation_geometry\Plugin\Field\FieldType

Code

protected static function getCenterFromCoordinates(array $coordinates) {
  $x = 0.0;
  $y = 0.0;
  $z = 0.0;
  foreach ($coordinates as $coordinate) {
    $lat = $coordinate['latitude'] * pi() / 180;
    $lon = $coordinate['longitude'] * pi() / 180;
    $a = cos($lat) * cos($lon);
    $b = cos($lat) * sin($lon);
    $c = sin($lat);
    $x += $a;
    $y += $b;
    $z += $c;
  }
  $num_coords = count($coordinates);
  $x /= $num_coords;
  $y /= $num_coords;
  $z /= $num_coords;
  $lon = atan2($y, $x);
  $hyp = sqrt($x * $x + $y * $y);
  $lat = atan2($z, $hyp);
  return [
    'latitude' => $lat * 180 / pi(),
    'longitude' => $lon * 180 / pi(),
  ];
}