Created
September 18, 2015 22:13
-
-
Save davidvanvickle/e04a883e262871fdce10 to your computer and use it in GitHub Desktop.
If an array of coordinates is clockwise, convert it to counterclockwise.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Make coordinates counter-clockwise | |
http://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order | |
(x2-x1)(y2+y1) | |
point[0] = (5,0) edge[0]: (6-5)(4+0) = 4 | |
point[1] = (6,4) edge[1]: (4-6)(5+4) = -18 | |
point[2] = (4,5) edge[2]: (1-4)(5+5) = -30 | |
point[3] = (1,5) edge[3]: (1-1)(0+5) = 0 | |
point[4] = (1,0) edge[4]: (5-1)(0+0) = 0 | |
--- | |
-44 counter-clockwise | |
*/ | |
// counter | |
var arr1 = [{x:-117.99520254135132,y:34.000304304410228},{x:-117.99455881118774,y:33.997280094622781},{x:-117.98940896987915,y:33.99770704841373},{x:-117.99000978469849,y:34.001940890690349},{x:-117.99520254135132,y:34.000304304410228}]; | |
// clock | |
var arr2 = [{x:-118.02886962890625,y:33.884097379274905},{x:-117.78717041015625,y:33.93424531117312},{x:-117.91351318359375,y:33.80653802509606},{x:-117.75970458984375,y:33.77914733128647},{x:-118.00689697265625,y:33.687781758439364}]; | |
var isClock = function (arr) { | |
var sums = []; | |
var sum = 0; | |
var len = arr.length; | |
var i2 = function (cur) { | |
if ((cur+1) >= len) return 0; | |
return (cur+1); | |
}; | |
for (var i=0; i < len; i++) { | |
// (x2-x1)(y2+y1) | |
sums.push( (arr[i2(i)].x - arr[i].x) * (arr[i2(i)].y + arr[i].y) ); | |
} | |
for (k in sums) sum += sums[k]; | |
console.log(sum); | |
return (sum > 0); | |
}; | |
var makeCounterClock = function (arr) { | |
if (isClock(arr)) { | |
console.log('clockwise, fixed'); | |
var cc = []; | |
for (var i=(arr.length-1); i > -1; i-- ) { | |
cc.push(arr[i]); | |
} | |
return cc; | |
} else { | |
console.log('counter-clockwise already'); | |
return arr; | |
} | |
}; | |
console.log( arr1 ); | |
console.log( makeCounterClock(arr1) ); | |
console.log( arr2 ); | |
console.log( makeCounterClock(arr2) ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment