Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Polygon Area

So I've gotten this code in javascript to calculate irregular polygon area from the net.

function polygonArea(X, Y, numPoints)  
{    
area = 0;  // Accumulates area in the loop   
j = numPoints-1;  // The last vertex is the 'previous' one to the first

  for (i=0; i<numPoints; i++)
  { area = area +  (X[j]+X[i]) * (Y[j]-Y[i]); 
      j = i;  //j is previous vertex to i
  }   
  return area/2; 
}

var xPts = [3, 3, 2, 2, 3, 3, 6, 6, 9, 9, 4, 4 ];
var yPts = [2, 4, 4, 5, 5, 6, 6, 5, 5, 3, 3, 2];

var a = polygonArea(xPts, yPts, 4); 
alert("Area  = " + a);

The results seems to be correct. if the vertex traced by clock-wise direction, it will shows positive results however it will become negative if i traced vertex in anti clockwise direction. Why is that so?

How does this algorithm work? i really want to know what is the mathematical explanation behind it, because i am still having a hard time to understand the explanation on the net.

like image 697
Charlie Kee Avatar asked Apr 29 '13 17:04

Charlie Kee


People also ask

What is the formula for a polygon?

Polygon Formula The important polygon formulas are: The sum of interior angles of a polygon with “n” sides =180°(n-2) Number of diagonals of a “n-sided” polygon = [n(n-3)]/2. The measure of interior angles of a regular n-sided polygon = [(n-2)180°]/n.

How do you find the area of a polygon with 5 sides?

The basic formula for the area of a regular pentagon is, Area of pentagon = 1/2 × p × a; where 'p' is the perimeter of the pentagon and 'a' is the apothem of a pentagon.

How do you find the area of a polygon with n sides?

What is the formula for the area of a regular polygon of n-sides? The formula for the area of a regular polygon of n-sides is [l2n]/[4tan(180/n)] Square units, where l is the side length of the polygon and n is the number of sides.

How do you find the area of a 3 sided polygon?

If you want to find the area of a regular triangle, all you have to do is follow this formula: area = 1/2 x base x height. If you have a triangle with a base of 10 and a height of 8, then the area = 1/2 x 8 x 10, or 40.


1 Answers

There is an algorithm to calculate polygon area:

function calcPolygonArea(vertices) {
    var total = 0;

    for (var i = 0, l = vertices.length; i < l; i++) {
      var addX = vertices[i].x;
      var addY = vertices[i == vertices.length - 1 ? 0 : i + 1].y;
      var subX = vertices[i == vertices.length - 1 ? 0 : i + 1].x;
      var subY = vertices[i].y;

      total += (addX * addY * 0.5);
      total -= (subX * subY * 0.5);
    }

    return Math.abs(total);
}
like image 57
Andrii Verbytskyi Avatar answered Sep 29 '22 05:09

Andrii Verbytskyi