Monday 2 January 2017

Creating random points along polyline in QGIS?


I am trying to create random points along a polyline shapefile in QGIS. Basically, like the 'random points' tool in 'research tools' but for polylines instead of polygons.



I have tried converting the line file to a polygon shapefile, but it fills in some areas with polygons, whereas other areas remain long line-type polygons.


I am pretty new to QGIS, and am not really familiar with Python code.



Answer



This code will work on the lastest dev build of QGIS.


from qgis.utils import iface
from qgis.core import *
from PyQt4.QtCore import QVariant
import random

def createRandomPoints(count):

# Create a new memory layer to store the points.
vl = QgsVectorLayer("Point", "distance nodes", "memory")
pr = vl.dataProvider()
pr.addAttributes( [ QgsField("distance", QVariant.Int) ] )
layer = iface.mapCanvas().currentLayer()

# For each selected object
for feature in layer.selectedFeatures():
geom = feature.geometry()
length = geom.length()

feats = []
# Loop until we reach the needed count of points.
for i in xrange(0,count):
# Get the random distance along the line.
distance = random.uniform(0, length)
# Work out the location of the point at that distance.
point = geom.interpolate(distance)

# Create the new feature.
fet = QgsFeature()

fet.setAttributeMap( { 0 : distance } )
fet.setGeometry(point)
feats.append(fet)

pr.addFeatures(feats)
vl.updateExtents()

QgsMapLayerRegistry.instance().addMapLayer(vl)

I know you said you are not very familiar with Python code but you should be able to run this pretty easy. Copy the above code into a file (mine is called locate.py) and place it in your ~/.qgis/python if you are on Windows 7 that will be in C:\Users\{your user name}\.qgis\python\ or on Windows XP C:\Documents and Settings\{your user name}\.qgis\python\



Once the file is in the python folder open QGIS and select some line objects.
Layer selection


Then open the Python console and run the following code:


import locate.py 
locate.createRandomPoints(10)

Python Console


The result should look something like this


Results


If you want to run it again just select some more lines and run locate.createRandomPoints(10) in the Python console again.



Note: locate.createRandomPoints(10) the 10 here is the number of points to generate per line


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...