I run a small calculator site, and the question I get most is some version of "how do I measure a shape that isn't a rectangle?" A garden bed with a bend in it, a room with an alcove, a plot with one crooked boundary. The nice surprise is that for any shape made of straight edges, one short formula does the whole job.
The shoelace formula in plain words
Walk around the shape and write down the corner coordinates in order. For each pair of neighbouring corners, multiply the x of the first by the y of the next, then subtract the x of the next times the y of the first. Add all of those up, take the absolute value, and halve it.
The code
function polygonArea(points) {
let sum = 0;
for (let i = 0; i < points.length; i++) {
const [x1, y1] = points[i];
const [x2, y2] = points[(i + 1) % points.length];
sum += x1 * y2 - x2 * y1;
}
return Math.abs(sum) / 2;
}
function polygonPerimeter(points) {
let total = 0;
for (let i = 0; i < points.length; i++) {
const [x1, y1] = points[i];
const [x2, y2] = points[(i + 1) % points.length];
total += Math.hypot(x2 - x1, y2 - y1);
}
return total;
}
The % points.length is what closes the shape by joining the last corner back to the first.
Try it on an L shaped room
const room = [[0, 0], [6, 0], [6, 2], [2, 2], [2, 5], [0, 5]];
console.log(polygonArea(room)); // 18
console.log(polygonPerimeter(room)); // 22
You can check it by hand: a 6 by 2 strip plus a 2 by 3 block is 12 + 6 = 18.
Mistakes I made so you don't have to
- Keep the corners in order. Clockwise or anticlockwise both work. Random order gives nonsense.
- Edges must not cross. A figure eight shape breaks the formula.
- GPS needs converting first. Raw latitude and longitude are not equal distances, so project them to a flat system before using this.
- Land units differ by region. A marla is commonly 272.25 square feet but varies, so keep it as one constant you can change.
Where I use it
I turned this into a free calculator, and you can play with it here: https://areaofirregularshapescalc.com/ (disclosure: it's my own project).
I handle curved edges by splitting them into lots of tiny straight segments. How do you deal with curves? I'd love to hear better ideas.
Top comments (0)