From f80cad531bb24c135b1b17fdca88e0f5b4cc9f27 Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Mon, 2 Dec 2013 12:05:04 +0100 Subject: [PATCH] Add ol.geom.flat.linearRingArea --- src/ol/geom/flatgeom.js | 22 ++++++++++++++++++++++ test/spec/ol/geom/flatgeom.test.js | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/ol/geom/flatgeom.js b/src/ol/geom/flatgeom.js index 4add38c2d8..93913e83e0 100644 --- a/src/ol/geom/flatgeom.js +++ b/src/ol/geom/flatgeom.js @@ -257,6 +257,28 @@ ol.geom.flat.lineStringLength = function(flatCoordinates, offset, end, stride) { }; +/** + * @param {Array.} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {number} Area. + */ +ol.geom.flat.linearRingArea = function(flatCoordinates, offset, end, stride) { + var twiceArea = 0; + var x1 = flatCoordinates[end - stride]; + var y1 = flatCoordinates[end - stride + 1]; + for (; offset < end; offset += stride) { + var x2 = flatCoordinates[offset]; + var y2 = flatCoordinates[offset + 1]; + twiceArea += x1 * y2 - y1 * x2; + x1 = x2; + y1 = y2; + } + return Math.abs(twiceArea / 2); +}; + + /** * @param {Array.} flatCoordinates Flat coordinates. * @param {number} offset Offset. diff --git a/test/spec/ol/geom/flatgeom.test.js b/test/spec/ol/geom/flatgeom.test.js index 0f1ca8ea77..9d709d12dd 100644 --- a/test/spec/ol/geom/flatgeom.test.js +++ b/test/spec/ol/geom/flatgeom.test.js @@ -127,6 +127,20 @@ describe('ol.geom.flat', function() { }); + describe('ol.geom.flat.linearRingArea', function() { + + it('calcaultes the area of a triangle', function() { + var area = ol.geom.flat.linearRingArea([0, 0, 0.5, 1, 1, 0], 0, 6, 2); + expect(area).to.be(0.5); + }); + + it('calculates the area of a unit square', function() { + var area = ol.geom.flat.linearRingArea([0, 0, 0, 1, 1, 1, 1, 0], 0, 8, 2); + expect(area).to.be(1); + }); + + }); + describe('ol.geom.flat.linearRingIsClockwise', function() { it('identifies clockwise rings', function() {