Skip to content

Instantly share code, notes, and snippets.

@willbreitkreutz
Created April 30, 2014 12:52
Show Gist options
  • Save willbreitkreutz/0a18cf4059269cfe4783 to your computer and use it in GitHub Desktop.
Save willbreitkreutz/0a18cf4059269cfe4783 to your computer and use it in GitHub Desktop.
Given an array of [x,y], sort the array in counter clockwise order, or specify ccw=false to sort in clockwise order.
var sortCCW = function(points,ccw){
//find the centroid or average of the points
var avg = [];
var x = 0;
var y = 0;
for (var i = 0; i < points.length; i++){
x = x + Number(points[i][0]);
y = y + Number(points[i][1]);
}
avg[0] = x/points.length;
avg[1] = y/points.length;
//function to return the bearing between two points, center and other point
var bearing = function(c,p){
var lon1 = c[0];
var lat1 = c[1];
var lon2 = p[0];
var lat2 = p[1];
var dlat = lat2 - lat1;
var dlon = lon2 - lon1;
var b
b = Math.atan2(dlat, dlon) * 180 / Math.PI;
return b;
}
//add the bearing to each of the points as a third element in the vertex
for (var i = 0; i < points.length; i++){
points[i][2] = bearing(avg,points[i]);
}
//sort the points by bearing
points.sort(function(a,b){
var x = a[2];
var y = b[2];
return y-x;
})
//strip out the bearing values to return a sorted copy of the original array
var newPoints = [];
for(var i = 0; i < points.length; i++){
newPoints.push([points[i][0],points[i][1]]);
}
//return the arrays reverse to get it CCW, unless the call overrides it with ccw=false
if(ccw===false){
return newPoints;
}else{
return newPoints.reverse();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment