Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgis random point inside a polygon

If i have a polygon in Postgis how can i find/calculate random points inside the polygon?

like image 523
Argiropoulos Stavros Avatar asked Jul 27 '10 11:07

Argiropoulos Stavros


1 Answers

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;
like image 169
Peter Krauss Avatar answered Sep 24 '22 00:09

Peter Krauss