Generating points along a line

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.

Getting ready

You will need to download the zipped shapefile and place it in a directory named shapes in your qgis_data directory from the following:

https://geospatialpython.googlecode.com/svn/path.zip

How to do it...

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:

  1. First, we need to import the processing module:
    import processing
    
  2. Then, we'll load the line layer onto the map:
    line = QgsVectorLayer("/qgis_data/shapes/path.shp", "Line", "ogr")
    QgsMapLayerRegistry.instance().addMapLayer(line)
    
  3. Next, we'll generate points along the line by specifying the path to the shapefile, a maximum distance between the points in map units (meters), the type of feature we want to output (vertices), extent, snap tolerance option, minimum distance between the points, output type, and output name. We won't specify the name and tell QGIS to load the output automatically:
    processing.runandload("grass:v.to.points",line,"1000",False, False,True,"435727.015026,458285.819185,5566442.32879,5591754.78979",-1,0.0001,0,None)
    
  4. Finally, we'll create some points within the lines' extent and load them as well:
    processing.runandload("qgis:randompointsinextent","435727.015026,458285.819185,5566442.32879,5591754.78979",100,100,None)
    

How it works...

The first algorithm puts the points on the line. The second places them within the vicinity. Both approaches have different use cases.

There's more...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset