Skip to content

Instantly share code, notes, and snippets.

@ArrEssJay
Created October 7, 2019 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArrEssJay/a53e3277ee937d47f266b2875e20c118 to your computer and use it in GitHub Desktop.
Save ArrEssJay/a53e3277ee937d47f266b2875e20c118 to your computer and use it in GitHub Desktop.
QGIS Geometry generator example - Random polygon grid fill (generates a multipoint geometry)
from qgis.core import *
from qgis.gui import *
import math
import random
"""
Define a grid based on the interval and the bounding box of
the feature. Grid will minimally cover the feature and be centre aligned
Create a multi-point geometry at the grid intersections where
the grid is enclosed by the feature - i.e. apply a clipping mask
Random value determines amount of randomness in X/Y within its
grid square a particular feature is allowed to have
"""
@qgsfunction(args='auto', group='Custom')
def fillGrid(xInterval, yInterval, rand, feature, parent):
box = feature.geometry().boundingBox()
#Create a grid that minimally covers the boundary
#using the supplied intervals and centre it
countX = math.ceil(box.width() / xInterval)
countY = math.ceil(box.height() / yInterval)
#Align the grid
gridX = countX * xInterval
gridY = countY * yInterval
dX= gridX - box.width()
dY= gridY - box.height()
xMin = box.xMinimum() - (dX/2)
yMin = box.yMinimum() - (dY/2)
points = []
#+1 to draw a symbol on the n+1th grid element
for xOff in range(countX+1):
for yOff in range(countY+1):
ptX = xMin + xOff*(xInterval) + rand * random.uniform(0,xInterval)
ptY = yMin + yOff*(yInterval) + rand * random.uniform(0,xInterval)
pt = QgsPointXY(ptX,ptY)
point = QgsGeometry.fromPointXY(pt)
if feature.geometry().contains(point):
points.append(pt)
return QgsGeometry.fromMultiPointXY(points)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment