Skip to content

Instantly share code, notes, and snippets.

@geozelot
Last active March 27, 2022 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geozelot/ddf88a9ae0438d7a46f176e9555ce7a1 to your computer and use it in GitHub Desktop.
Save geozelot/ddf88a9ae0438d7a46f176e9555ce7a1 to your computer and use it in GitHub Desktop.
PostgreSQL/PostGIS - Create regular (equilateral & equiangular) Polygons (i.e. Hexagons, Pentagons, ...).
/*
* @in_params
* center - center POINT geometry
* radius - circumradius [in CRS units] (cirlce that inscribes the *gon)
* sides - desired side count (e.g. 6 for Hexagon)
* skew - rotation offset, clockwise [in degree]; DEFAULT 0.0 (corresponds to planar NORTH)
*
* @out_params
* agon - resulting *gon POLYGON geometry
*
*
* The function will create a @sides sided regular, equilateral & equiangular Polygon
* from a given @center and @radius and optional @skew offset from NORTH
*/
CREATE OR REPLACE FUNCTION ST_MakeAGon(
IN center GEOMETRY(POINT),
IN radius FLOAT8,
IN sides INT,
IN skew FLOAT8 DEFAULT 0.0,
OUT agon GEOMETRY(POLYGON)
) LANGUAGE 'plpgsql' IMMUTABLE STRICT PARALLEL SAFE AS
$$
DECLARE
_x FLOAT8 := ST_X($1);
_y FLOAT8 := ST_Y($1);
_cr FLOAT8 := 360.0/$3;
__v GEOMETRY(POINT)[];
BEGIN
FOR i IN 0..$3 LOOP
__v[i] := ST_MakePoint(_x + $2*SIND(i*_cr + $4), _y + $2*COSD(i*_cr + $4));
END LOOP;
agon := ST_MakePolygon(ST_MakeLine(__v));
END;
$$
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment