Skip to content

Instantly share code, notes, and snippets.

@stuartlynn
Created February 22, 2016 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stuartlynn/95775e3a8f09e3f14989 to your computer and use it in GitHub Desktop.
Save stuartlynn/95775e3a8f09e3f14989 to your computer and use it in GitHub Desktop.
dot_density.sql
CREATE OR REPLACE FUNCTION cdb_dot_density(g geometry , no_points Integer, max_iter Integer DEFAULT 1000 )
RETURNS setof geometry AS
$$
DECLARE
extent GEOMETRY;
test_point Geometry;
width NUMERIC;
height NUMERIC;
x0 NUMERIC;
y0 NUMERIC;
xp NUMERIC;
yp NUMERIC;
no_left INTEGER;
points GEOMETRY[];
BEGIN
extent := ST_Envelope(g);
width := ST_XMax(extent) - ST_XMIN(extent);
height := ST_YMax(extent) - ST_YMIN(extent);
x0 := ST_XMin(extent);
y0 := ST_YMin(extent);
no_left := no_points;
LOOP
if(no_left=0) THEN
EXIT;
END IF;
xp = x0 + width*random();
yp = y0 + height*random();
test_point = CDB_LATLNG(yp,xp);
IF(ST_Contains(g, test_point)) THEN
no_left = no_left - 1;
RETURN NEXT test_point;
END IF;
END LOOP;
END
$$
LANGUAGE plpgsql VOLATILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment