QGIS-Processing-tools
QGIS-Processing-tools copied to clipboard
Adapt script to output single route
Hi there, thanks for sharing this script!
I've one issue though: I try to adapt the script to add only one feature which contains all route points, like below (altered code sections are marked with ###):
#https://github.com/anitagraser/QGIS-Processing-tools/blob/master/2.2/scripts/point_layer_to_route.py
#Definition of inputs and outputs
#==================================
##Routing tools=group
##points=vector
##network=vector
##route=output vector
#Algorithm body
#==================================
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *
from processing.core.VectorWriter import VectorWriter
point_layer = processing.getObject(points)
network_layer = processing.getObject(network)
writer = VectorWriter(route, None, [QgsField("order", QVariant.Int)], network_layer.dataProvider().geometryType(), network_layer.crs() )
# prepare graph
vl = network_layer
director = QgsLineVectorLayerDirector( vl, -1, '', '', '', 3 )
properter = QgsDistanceArcProperter()
director.addProperter( properter )
crs = vl.crs()
builder = QgsGraphBuilder( crs )
# prepare points
features = processing.features(point_layer)
point_count = point_layer.featureCount()
points = []
for f in features:
points.append(f.geometry().asPoint())
tiedPoints = director.makeGraph( builder, points )
graph = builder.graph()
route_vertices = []
### I've put this to global scope
route_points = []
for i in range(0,point_count-1):
progress.setPercentage(int(100 * i/ point_count))
from_point = tiedPoints[i]
to_point = tiedPoints[i+1]
from_id = graph.findVertex(from_point)
to_id = graph.findVertex(to_point)
(tree,cost) = QgsGraphAnalyzer.dijkstra(graph,from_id,0)
if tree[to_id] == -1:
continue # ignore this point pair
else:
# collect all the vertices between the points
curPos = to_id
while (curPos != from_id):
route_points.append( graph.vertex( graph.arc( tree[ curPos ] ).inVertex() ).point() )
curPos = graph.arc( tree[ curPos ] ).outVertex()
route_points.append(from_point)
### ...and have put this out of the above loop
fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromPolyline( route_points ))
writer.addFeature(fet)
del writer
However, this will yield a closed line. Sorry, but I didn't quite grasp the logic behind the ordering of the route_points being added to the array - that's why I didn't manage to alter the code to do what I want..