You can generate points within a polygon in a fairly simple way by using the point in polygon method. However, sometimes you may want to generate points along a line. You can randomly place points inside the polygon's extent — which is essentially just a rectangular polygon — or you can place points at random locations along the line at random distances. In this recipe, we'll demonstrate both of these methods.
You will need to download the zipped shapefile and place it in a directory named shapes
in your qgis_data
directory from the following:
First, we will generate random points along a line using a grass()
function in the Processing Toolbox. Then, we'll generate points within the line's extent using a native QGIS processing function. To do this, we need to perform the following steps:
import processing
line = QgsVectorLayer("/qgis_data/shapes/path.shp", "Line", "ogr") QgsMapLayerRegistry.instance().addMapLayer(line)
processing.runandload("grass:v.to.points",line,"1000",False, False,True,"435727.015026,458285.819185,5566442.32879,5591754.78979",-1,0.0001,0,None)
processing.runandload("qgis:randompointsinextent","435727.015026,458285.819185,5566442.32879,5591754.78979",100,100,None)
The first algorithm puts the points on the line. The second places them within the vicinity. Both approaches have different use cases.
Another option will be to create a buffer around the line at a specified distance and clip the output of the second algorithm so that the points aren't near the corners of the line extent. The QgsGeometry
class also has an interpolate which allows you to create a point on a line at a specified distance from its origin. This is documented at http://qgis.org/api/classQgsGeometry.html#a8c3bb1b01d941219f2321e6c6c3db7e1.