From 43d67736a8097532780ba07bfea9e5d06a5e7b38 Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Mon, 11 Nov 2013 20:15:49 +0100 Subject: [PATCH] Add ol.geom.flatLinearRingIsClockwise --- src/ol/geom/geometry.js | 25 +++++++++++++++++++++++++ test/spec/ol/geom/geom.test.js | 18 ++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/ol/geom/geometry.js b/src/ol/geom/geometry.js index e6a75e5c94..4124ee04df 100644 --- a/src/ol/geom/geometry.js +++ b/src/ol/geom/geometry.js @@ -360,6 +360,31 @@ ol.geom.flatLinearRingContainsXY = }; +/** + * @param {Array.} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {boolean} Is clockwise. + */ +ol.geom.flatLinearRingIsClockwise = + function(flatCoordinates, offset, end, stride) { + // http://tinyurl.com/clockwise-method + // https://github.com/OSGeo/gdal/blob/trunk/gdal/ogr/ogrlinearring.cpp + var edge = 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]; + edge += (x2 - x1) * (y2 + y1); + x1 = x2; + y1 = y2; + } + return edge > 0; +}; + + /** * @param {Array.} flatCoordinates Flat coordinates. * @param {number} offset Offset. diff --git a/test/spec/ol/geom/geom.test.js b/test/spec/ol/geom/geom.test.js index 6908756e66..1c7c8749ef 100644 --- a/test/spec/ol/geom/geom.test.js +++ b/test/spec/ol/geom/geom.test.js @@ -54,6 +54,24 @@ describe('ol.geom', function() { }); + describe('ol.geom.flatLinearRingIsClockwise', function() { + + it('identifies clockwise rings', function() { + var flatCoordinates = [0, 1, 1, 4, 4, 3, 3, 0]; + var isClockwise = ol.geom.flatLinearRingIsClockwise( + flatCoordinates, 0, flatCoordinates.length, 2); + expect(isClockwise).to.be(true); + }); + + it('identifies anti-clockwise rings', function() { + var flatCoordinates = [2, 2, 3, 2, 3, 3, 2, 3]; + var isClockwise = ol.geom.flatLinearRingIsClockwise( + flatCoordinates, 0, flatCoordinates.length, 2); + expect(isClockwise).to.be(false); + }); + + }); + describe('ol.geom.reverseFlatCoordinates', function() { describe('with a stride of 2', function() {