You are here

public function Polygon::centroid in geoPHP 8

Same name and namespace in other branches
  1. 7 geoPHP/lib/geometry/Polygon.class.php \Polygon::centroid()

Overrides Collection::centroid

File

geoPHP/lib/geometry/Polygon.class.php, line 44

Class

Polygon
Polygon: A polygon is a plane figure that is bounded by a closed path, composed of a finite sequence of straight line segments

Code

public function centroid() {
  if ($this
    ->isEmpty()) {
    return NULL;
  }
  if ($this
    ->geos()) {
    return geoPHP::geosToGeometry($this
      ->geos()
      ->centroid());
  }
  $exterior_ring = $this->components[0];
  $pts = $exterior_ring
    ->getComponents();
  $c = count($pts);
  if ((int) $c == '0') {
    return NULL;
  }
  $cn = array(
    'x' => '0',
    'y' => '0',
  );
  $a = $this
    ->area(TRUE, TRUE);

  // If this is a polygon with no area. Just return the first point.
  if ($a == 0) {
    return $this
      ->exteriorRing()
      ->pointN(1);
  }
  foreach ($pts as $k => $p) {
    $j = ($k + 1) % $c;
    $P = $p
      ->getX() * $pts[$j]
      ->getY() - $p
      ->getY() * $pts[$j]
      ->getX();
    $cn['x'] = $cn['x'] + ($p
      ->getX() + $pts[$j]
      ->getX()) * $P;
    $cn['y'] = $cn['y'] + ($p
      ->getY() + $pts[$j]
      ->getY()) * $P;
  }
  $cn['x'] = $cn['x'] / (6 * $a);
  $cn['y'] = $cn['y'] / (6 * $a);
  $centroid = new Point($cn['x'], $cn['y']);
  return $centroid;
}