Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix direction of Polygon ring coordinates #76

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/poly.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ module.exports.write = function writePoints(geometries, extent, shpView, shxView
shxI = 0,
shxOffset = 100;

//Ensure polygon rings are ordered in correct direction
if(TYPE === types.geometries.POLYGON){
geometries = geometries.reduce(function(geom_acc, poly){
var flipped = poly.reduce(function(poly_acc, ring, idx){
//External rings must be clockwise, Internal must be counter-clockwise
idx == 0
? isClockwise(ring) ? poly_acc.push(ring) : poly_acc.push(ring.reverse())
: isClockwise(ring) ? poly_acc.push(ring.reverse()) : poly_acc.push(ring);
return poly_acc;
}, []);
geom_acc.push(flipped);
return geom_acc;
}, []);
}
geometries.forEach(writePolyLine);

function writePolyLine(coordinates, i) {
Expand Down Expand Up @@ -62,6 +76,16 @@ module.exports.write = function writePoints(geometries, extent, shpView, shxView

shpI += contentLength + 8;
}

//Takes a ring of coordinates. Returns true if they're defined in clockwise order
function isClockwise(ring){
var sum = 0;
for(var i = 0; i < ring.length; i++){
var prevIdx = i == 0 ? ring.length - 1 : i - 1;
sum += (ring[i][0] - ring[prevIdx][0])*(ring[i][1] + ring[prevIdx][1]);
}
return sum > 0 ? true : false;
}
};

module.exports.shpLength = function(geometries) {
Expand Down