postgresql - Rotate Polygon to be Parallel with the X Axis -
by default, postgis calculates envelope or extent of polygon based on bounding box of polygon ((minx, miny), (minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny))
.
this gives result so:
however, i'm looking result more this:
as far know, best algorithm can come is:
- determine angle
a
rotate polygonx
parallel x-axis - rotate
x
a
degrees, calculate envelopey
of rotated polygonx
- rotate
y
-a
degrees
how calculate step #1 in postgis?
here's implementation. doesn't handle degenerate cases , may not rectangle chose if areas tie. i'm working on submission postgis, should enough work until patch postgis.
create or replace function st_minimumrectangle(g geometry) returns geometry language 'plpgsql' $$ declare hull geometry; begin hull = st_exteriorring(st_convexhull(g)); -- 1 side must lie along rectangle. -- so, each side, rotate, bbox, counter-rotate bbox sides ( select st_pointn(hull, n) a, st_pointn(hull, n+1) b, n side generate_series(1,st_npoints(hull)-1) n ), angles ( select side, a, b, st_azimuth(a, b) angle sides ), boxes ( select st_rotate(st_envelope(st_rotate(hull, -angle)),angle) rect, side, angle angles ) select rect hull boxes order st_area(rect), side limit 1 ; return hull; end; $$ immutable strict;
Comments
Post a Comment