I need to create a grid within a polygon like it is done in

How to create regular point grid inside a polygon in Postgis?

There a function is created to draw the grid points. But necessary to know is how huge the cells are or how huge is the distance between the point. In my case I don't know anything about that. I just know how much grid cells should be created. How can I solve that problem? How is it possible to create a grid without knowing the cell size but the number of cells that should be created? Does anybody can help me?

  • do you have a polygon geometry?
    – Krystian
    Commented Jun 10, 2015 at 13:31
  • yes, input objects are a polygon geometry and the number of grid cells
    – Bine
    Commented Jun 10, 2015 at 13:36
  • ok, and is it will be ok if on the edges of polygon grid would be cutted to polygon area?
    – Krystian
    Commented Jun 10, 2015 at 13:41
  • yes, thats no problem
    – Bine
    Commented Jun 10, 2015 at 13:45
  • 1
    Do you need an exact number? I suspect that it is likely with an irregular polygon as input that a small change in grid might overshoot or undershoot in some cases. You would need to write an iterative function with some initial guess for grid spacing and increase/decrease this until you are close to the cell number you are looking for. Commented Jun 10, 2015 at 14:16

1 Answer 1


You can adapt the function in the linked question. Divide the problem into two parts:

  1. Estimate the point spacing
  2. Create the points

For step 1, divide ST_Area(geom) by the required number of points to get the area per point (I'm assuming n is large), then take the square root to get the separation. So, assuming you've chosen one implementation of makegrid(geometry, real) from that question,

makegrid(geom, sqrt(ST_Area(geom) / n)

If you need to return exactly n points, adapt this inside an iterative search for the best separation.

N.B. I've assumed real-valued separation because I don't know the units of your grid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.