Sort latitude and longitude coordinates into clockwise ordered quadrilateral

后端 未结 3 728
暗喜
暗喜 2020-12-13 00:54

Problem

Users can provide up to four latitude and longitude coordinates, in any order. They do so with Google Maps. Using Google\'s Polygon

3条回答
  •  春和景丽
    2020-12-13 01:22

    Algorithm idea: average the four points to get a point inside the polygon. Then calculate the angle of the ray between that center point and each point, using inverse trigonometric functions, like explained here. Then sort by the angles. That should give you a (counter-)clockwise ordering, depending on the sort order and what you consider "zero degrees".

    UPDATE: here's some code. Mostly untested, but it's the idea.

    function sorted_points(points) {
        points = points.slice(0); // copy the array, since sort() modifies it
        var stringify_point = function(p) { return p.x + ',' + p.y; };
    
        // finds a point in the interior of `pts`
        var avg_points = function(pts) {
            var x = 0;
            y = 0;
            for(i = 0; i < pts.length; i++) {
                x += pts[i].x;
                y += pts[i].y;
            }
            return {x: x/pts.length, y:y/pts.length};
        }
        var center = avg_points(points);
    
        // calculate the angle between each point and the centerpoint, and sort by those angles
        var angles = {};
        for(i = 0; i < points.length; i++) {
            angles[stringify_point(points[i])] = Math.atan(points[i].x - center.x, points[i].y - center.y);
        }
        points.sort(function(p1, p2) {
            return angles[stringify_point(p1)] - angles[stringify_point(p2)];
        });
        return points;
    }
    

    It sorts points (an array of objects like {x: 1, y: 1}) counter-clockwise.

提交回复
热议问题