Random Postgis Point Inside Polygon

If I have a polygon in Postgis, how can I find-calculate random points inside this polygon?

+5
source share
1 answer

There is no code in the link provided by @Mike, but there are good tips from Dr.JTS: "point density" ... "Essentially, this is connected with creating a set of N randomly located points that lie in a given polygon." The function does this: the input is a polygon, random points are output.

These links have the same SQL / PostGIS function RandomPoint(Geometry): sorokine 2011 and osgeo.org/postgis/wiki . The second link (wiki) is more complete, explaining and demonstrating examples, and the function RandomPointsInPolygon(geometry,integer)is the answer to the problem.

The solion extension for entering "point density per area" or the 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;
+5
source

All Articles