concept grid in category postgis

appears as: grid, grids, grid
PostGIS in Action, Third Edition

This is an excerpt from Manning's book PostGIS in Action, Third Edition.

  • Raster--The multi-band cell type. Rasters model space as a grid of rectangular cells, each containing a numeric array of values.
  • Listing 11.4 uses a square gridding function ST_SquareGrid(postgis.net/docs/manual-3.1/ST_SquareGrid.html) introduced in PostGIS 3.1. ST_SquareGrid is a set returning function that returns a table consisting of 3 columns (i,j,geom). The i is the row number along the grid and j is the column number along the grid.

    Listing 11.4. Dividing the NYC boroughs into rectangular blocks
    WITH bounds AS (
         SELECT ST_SetSRID(ST_Extent(geom), ST_SRID(geom)) AS geom #1
            FROM ch11.boroughs
        GROUP BY ST_SRID(geom)
     ),
     grid AS (SELECT g.i, g.j, g.geom   #2
              FROM bounds, ST_SquareGrid(10000,bounds.geom) AS g
              )
     SELECT b.boroname, grid.i, grid.j,
          CASE WHEN ST_Covers(b.geom,grid.geom) THEN grid.geom
          ELSE ST_Intersection(b.geom, grid.geom) END AS geom #3
     INTO ch11.boroughs_square_grid #4
     FROM ch11.boroughs AS b
         INNER JOIN grid ON ST_Intersects(b.geom, grid.geom);
    
    CREATE INDEX ix_boroughs_square_grid  #5
     ON ch11.boroughs_square_grid
       USING gist(geom);

    Listing 11.4 uses a grid where each square is 10,000 units in length/width and spans the full extent of NYC boroughs. Since the boroughs are in NY State plane feet (SRID=2263), the units of measure are square feet. When you clip the bouroughs by the grid, the resulting tiles have various shapes and sizes when they are on bourough boundaries. This may not be ideal if you want all your tiles to be the same size. In those cases you may want to forgo the clipping and just return the squares as is. Note that <3> uses a CASE statement. This is equivalent in result to just doing ST_Intersection, but because ST_Intersection is an intensive operation, you save a lot of processing cycles by just returning the square if it is completely covered by the borough.

    Listing 11.4 defined a bounds that covered the whole area of interest and split that into squares and then clipped the geometries using those squares. One feature of the ST_SquareGrid function that is not obvious from listing 11.4 is that for any given SRID and size there is a unique dicing of grids that can be formed across all space. Which means for any given SRID and size a particular point will have exactly the same i,j, geom tile it intersects in. This means that instead of figuring out the extent of the point of interest first, you could achieve the same result with listing 11.5.