# How to create regular point grid inside a polygon in Postgis without knowing cell size but cell number?

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 Jun 10 '15 at 13:31
• yes, input objects are a polygon geometry and the number of grid cells – Bine Jun 10 '15 at 13:36
• ok, and is it will be ok if on the edges of polygon grid would be cutted to polygon area? – Krystian Jun 10 '15 at 13:41
• yes, thats no problem – Bine Jun 10 '15 at 13:45
• 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. – John Powell Jun 10 '15 at 14:16

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.