Thursday, 28 February 2019

Filling polygons with points or polygons using PyQGIS?



I am trying to find a method to, as efficiently as possible, fill irregular shape polygons with points (defined spacing) or alternatively, polygons of defined size ( which i can find the point centroid).


I am using QGis, Python



Answer



Next PyQGIS code uses a defined spacing of 50 m for generating points inside each feature of polygon layers.


layer = iface.activeLayer()

feats = [ feat for feat in layer.getFeatures()]


points = []

spacing_y = 50
spacing_x = 50

for feat in feats:
extent = feat.geometry().boundingBox()
xmin, ymin, xmax, ymax = extent.toRectF().getCoords()

rows = int(ymax - ymin)/spacing_y

cols = int(xmax - xmin)/spacing_x

x = xmin
y = ymax

geom_feat = feat.geometry()

for i in range(rows+1):
for j in range(cols+1):
pt = QgsPoint(x,y)

tmp_pt = QgsGeometry.fromPoint(pt)
if tmp_pt.within(geom_feat):
points.append(tmp_pt.asPoint())
x += spacing_x
x = xmin
y -= spacing_y

epsg = layer.crs().postgisSrid()

#points

uri = "Point?crs=epsg:" + str(epsg) + "&field=id:integer""&index=yes"

mem_layer = QgsVectorLayer(uri,
'point',
'memory')

prov = mem_layer.dataProvider()

feats = [ QgsFeature() for i in range(len(points)) ]


for i, feat in enumerate(feats):
feat.setAttributes([i])
feat.setGeometry(QgsGeometry.fromPoint(points[i]))

prov.addFeatures(feats)

QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

After running the code at the Python Console of QGIS, with a two features polygon layer, I got:


enter image description here



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...