Sort list of coordinates

750 Views Asked by At

I have the following problem: I have a list of all the x, y coordinates of a polygon's points. I now need to sort them in such a way that I obtain the points in a clockwise order.

Currently I have the 6 coordinates to draw a polygon but its not in order.

Does anyone know how to accomplish that?

Input coordinates :

Coordinate: 506.6609866568262, 673.970398950142

Coordinate: 505.34898334317376, 682.8179210498581

Coordinate: 502.0723751660178, 680.523615304454

Coordinate: 534.3026433431738, 682.736131049858

Coordinate: 535.6146466568263, 673.8886089501419

Coordinate: 538.8912548339822, 676.1829146955461

Output coordinates :

Coordinate: 506.6609866568262, 673.970398950142

Coordinate: 502.0723751660178, 680.523615304454

Coordinate: 505.34898334317376, 682.8179210498581

Coordinate: 534.3026433431738, 682.736131049858

Coordinate: 538.8912548339822, 676.1829146955461

Coordinate: 535.6146466568263, 673.8886089501419

Thanks in advance,

1

There are 1 best solutions below

4
On BEST ANSWER

Use polar coordinates:

  1. find an internal point to the polygon as a reference, say (c,d);
  2. use atan2(x-c, y-d) for each vertex (x,y) of the polygon to get the polar angles from that internal point; then
  3. sort by the angles you get.

If the polygon is convex, averaging the max and min values of x and likewise for y should get you an internal point. Otherwise, you have more work to do.