[GIS] Creating regularly spaced, defined # of points within polygon in QGIS

polygonqgisvector-grid

I used the research tool "Regular Points" to produce a certain number of points within a polygon, but it forms a rectangular grid of points rather than only within the shape of the polygon. Since I need a certain number of points within the polygon, is there any way to do so without trial and error?

E.g. right now only 8 of the 25 points I want are within the polygon, but I want 25 points, so I could increase to 50 points and see how many then appear within the polygon

enter image description here

Best Answer

What QGIS is referring to in terms of the layer boundary is actually the envelope or bounding box of the geometry.

I've documented a solution which is probably the closest you will get to automating this is (short of filing a bug / feature request).

The process works based on the ratio between area of the two objects: the feature geometry and it's bounding box).

Check the following steps below:

  1. Select the layer you want to work on.

  2. Select the feature you wish to work on. Make sure nothing else is selected.

  3. Run the following snippet within the Python Console.

    layer = qgis.utils.iface.activeLayer()
    features = layer.selectedFeatures()
    feature = features[0]
    geom = feature.geometry()
    env_rect = geom.boundingBox()
    env_geom = QgsGeometry.fromRect(env_rect)
    env_geom.area() / geom.area()
    

    Be sure to push enter as the last line will not automatically return.

  4. Run the Regular Points tool again, but enter the number of points that you want inside the box multiplied by the output given by your script.

In my sample below, the result I received from the output was a value of ~2. I requested 20 dots to be output by the process where I actually only wanted 10. I was given 8 in return, which is fairly close. Depending on the actual shape you're using the results will vary.

If you were so inclined, you could automate (recursively) the Regular Points process modifying the variables until you arrived at your desired number.

Sample

Related Question