PHP: How to determine the center of a Polygon


How to determine the center of a Polygon.

Read first: PHP: How to calculate signed area of a Polygon

Method 1:

// Find the polygon's centroid.
function getCenter($polygon)
{ 
    $NumPoints = count($polygon);
    
    if($polygon[$NumPoints-1] == $polygon[0]){
        $NumPoints--;
    }else{
        //Add the first point at the end of the array.
        $polygon[$NumPoints] = $polygon[0];
    }
 
    // Find the centroid.
    $X = 0;
    $Y = 0;
    For ($pt = 0 ;$pt<= $NumPoints-1;$pt++){
        $factor = $polygon[$pt][0] * $polygon[$pt + 1][1] - $polygon[$pt + 1][0] * $polygon[$pt][1];
        $X += ($polygon[$pt][0] + $polygon[$pt + 1][0]) * $factor;
        $Y += ($polygon[$pt][1] + $polygon[$pt + 1][1]) * $factor;
    }

    // Divide by 6 times the polygon's area.
    $polygon_area = ComputeArea($polygon);
    $X = $X / 6 / $polygon_area;
    $Y = $Y / 6 / $polygon_area;

    return array($X, $Y);
}

Method 2:

function getCenter($polygon) {
    $NumPoints = count($polygon);
    
    if($polygon[$NumPoints-1] == $polygon[0]){
        $NumPoints--;
    }else{
        //Add the first point at the end of the array.
        $polygon[$NumPoints] = $polygon[0];
    }
    
    $x = 0;
    $y = 0;

    $lastPoint = $polygon[$NumPoints - 1];
     
    for ($i=0; $i<=$NumPoints - 1; $i++) {
        $point = $polygon[$i];
        $x += ($lastPoint[0] + $point[0]) * ($lastPoint[0] * $point[1] - $point[0] * $lastPoint[1]);
        $y += ($lastPoint[1] + $point[1]) * ($lastPoint[0] * $point[1] - $point[0] * $lastPoint[1]);
        $lastPoint = $point;
    }

    $x /= 6*ComputeArea($polygon);
    $y /= 6*ComputeArea($polygon);
 
    return array($x, $y);
}

Example 1:

$polygon = array(
    array(0,6),
    array(4,6),
    array(2,3),
    array(4,0),
    array(0,0),
    array(0,6),
);
var_dump(getCenter($polygon));

Result:

array(2) {
[0]=>
float(1.55555555556)
[1]=>
int(3)
}

Example 2:

$polygon = array(
    array(0,3),
    array(4,4),
    array(3,0),
    array(4,-4),
    array(0,-3),
    array(-4,-4),
    array(-3,0),
    array(-4,4),
    //array(0,3),
);
var_dump(getCenter($polygon));

Result:

array(2) {
[0]=>
int(0)
[1]=>
int(0)
}

Leave a Reply