If i have a polygon in Postgis how can i find/calculate random points inside the polygon?
The link cited by @Mike not have a code, but good clues from Dr.JTS: "dot-density" maps... "Essentially this involves creating a set of N randomly-placed points which lie within a given polygon". A function do this: the input is the polygon, the output the random points.
These links have the same SQL/PostGIS function RandomPoint(Geometry)
: sorokine 2011 and osgeo.org/postgis/wiki. The second link (wiki) is more complete, explaning and showing examples, and a function RandomPointsInPolygon(geometry,integer)
that is an answer to the problem.
Extending the solion to input "density of points per area", or average distance between points:
CREATE OR REPLACE FUNCTION RandomPointsInPolygon(
geom geometry, -- the polygon
avg_dist float DEFAULT 20.0, -- average of 20 units between points
min_pts integer DEFAULT 1, -- min. of points
max_pts integer DEFAULT 1000 -- max. of points
) RETURNS SETOF geometry AS
$$
SELECT CASE WHEN npts=1 THEN ST_Centroid($1)
ELSE RandomPointsInPolygon($1,npts)
END
FROM (
SELECT CASE WHEN d<$3 THEN $3 WHEN d>$4 THEN $4 ELSE d END AS npts
FROM (SELECT (st_area($1)/(pi()*($2/2.0)^2))::integer AS d) AS t
) AS t2;
$$ LANGUAGE SQL;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With