Skip to content

Instantly share code, notes, and snippets.

@tomplex
Last active January 30, 2019 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomplex/6d44713b259d36f2aa3f1a1ac344eb8e to your computer and use it in GitHub Desktop.
Save tomplex/6d44713b259d36f2aa3f1a1ac344eb8e to your computer and use it in GitHub Desktop.
Create a grid of equal-sized cells from an array of geometries in PostGIS
/*
Author: Tom Caruso
Divide up a box into multiple equal-size cells.
Helpful to split up a coverage of geometries into a gridded
Usage:
SELECT create_grid(array_agg(geom), 10, 10, 4326) FROM my_geometry_table;
*/
DROP TYPE IF EXISTS grid_record;
CREATE TYPE grid_record AS (cell_id INT, geom GEOMETRY);
DROP FUNCTION IF EXISTS create_grid(box, int, int, int);
CREATE OR REPLACE FUNCTION create_grid(box box2d, cells_x int = 2, cells_y int = 2, srid int = null)
RETURNS SETOF grid_record AS
$$
DECLARE
box_geom GEOMETRY;
geom GEOMETRY;
cell_id INT;
width FLOAT;
height FLOAT;
cell_x INT;
cell_y INT;
dx FLOAT;
dy FLOAT;
x_start FLOAT;
y_start FLOAT;
ret grid_record;
BEGIN
box_geom := box2d(box)::GEOMETRY;
width := st_xmax(box_geom) - st_xmin(box_geom);
height := st_ymax(box_geom) - st_ymin(box_geom);
dx := width / cells_x;
dy := height / cells_y;
cell_id := 1;
FOR cell_y IN 1..cells_y LOOP
y_start := st_ymax(box_geom) - (cell_y * dy);
FOR cell_x IN 0..(cells_x - 1) LOOP
x_start := st_xmin(box_geom) + (cell_x * dx);
geom := st_makebox2d(
st_makepoint(x_start, y_start),
st_makepoint(x_start + dx, y_start + dy)
)::GEOMETRY;
IF srid IS NOT NULL THEN
geom := st_setsrid(geom, srid);
END IF;
SELECT cell_id, geom INTO ret;
cell_id := cell_id + 1;
RETURN NEXT ret;
END LOOP;
END LOOP;
END;
$$ LANGUAGE plpgsql;
@diogocaribe
Copy link

I believe that I find a behaviour not expect. When I create a fishnet from polygon the result of grid has exceeded from limit of polygon source. Do you believe that it is possible to create a fishnet from polygon with the same size of original?

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment