Last active
September 13, 2019 09:16
-
-
Save justinlewis/4678493 to your computer and use it in GitHub Desktop.
Create a random point geometry within the boundaries of a specified polygon. Implemented as a PostGIS function. Inputs include the_geom (name of input polygon geometry field) and maxiter (max # of iterations to try placing point within the polygon).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Function: babysim_random_jobs_explode(geometry, integer) | |
-- DROP FUNCTION babysim_random_jobs_explode(geometry, integer); | |
CREATE OR REPLACE FUNCTION babysim_random_jobs_explode(the_geom geometry, maxiter integer DEFAULT 10000) | |
RETURNS geometry AS | |
$BODY$ | |
DECLARE | |
i INTEGER := 0; | |
x0 DOUBLE PRECISION; | |
dx DOUBLE PRECISION; | |
y0 DOUBLE PRECISION; | |
dy DOUBLE PRECISION; | |
xp DOUBLE PRECISION; | |
yp DOUBLE PRECISION; | |
rpoint Geometry; | |
BEGIN | |
-- find envelope | |
x0 = ST_XMin(the_geom); | |
dx = (ST_XMax(the_geom) - x0); | |
y0 = ST_YMin(the_geom); | |
dy = (ST_YMax(the_geom) - y0); | |
WHILE i < maxiter LOOP | |
i = i + 1; | |
xp = x0 + dx * random(); | |
yp = y0 + dy * random(); | |
rpoint = ST_SetSRID( ST_MakePoint( xp, yp ), ST_SRID(the_geom) ); | |
EXIT WHEN ST_Within( rpoint, the_geom ); | |
END LOOP; | |
IF i >= maxiter THEN | |
RAISE EXCEPTION 'RandomPoint: number of interations exceeded ', maxiter; | |
END IF; | |
RETURN rpoint; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE | |
COST 100; | |
ALTER FUNCTION babysim_random_jobs_explode(geometry, integer) | |
OWNER TO model_team; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment