I am looking for a method to automatically select the lines of a shortest path between two points. Theoretically it is the Road Graph plugin, which is now the "shortest path point to point" function in QGIS. My problem is that I don't want to create a new shapefile. I want to select the lines in the shapefile I am working with to insert data into the attribute table.
How can I solve this problem? I tried using Python, but I am new to Python and the scripts I tried don't work. For example, I found this script(https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/network_analysis.html?highlight=shortest#finding-shortest-paths). But nothing happens when I run it.
from qgis.core import *
from qgis.gui import *
from qgis.analysis import *
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
vectorLayer = QgsVectorLayer('testdata/network.gpkg|layername=network_lines', 'lines')
builder = QgsGraphBuilder(vectorLayer.sourceCrs())
director = QgsVectorLayerDirector(vectorLayer, -1, '', '', '', QgsVectorLayerDirector.DirectionBoth)
startPoint = QgsPointXY(1179661.925139,5419188.074362)
endPoint = QgsPointXY(1180942.970617,5420040.097560)
tiedPoints = director.makeGraph(builder, [startPoint, endPoint])
tStart, tStop = tiedPoints
graph = builder.graph()
idxStart = graph.findVertex(tStart)
tree = QgsGraphAnalyzer.shortestTree(graph, idxStart, 0)
idxStart = tree.findVertex(tStart)
idxEnd = tree.findVertex(tStop)
if idxEnd == -1:
raise Exception('No route!')
# Add last point
route = [tree.vertex(idxEnd).point()]
# Iterate the graph
while idxEnd != idxStart:
edgeIds = tree.vertex(idxEnd).incomingEdges()
if len(edgeIds) == 0:
break
edge = tree.edge(edgeIds[0])
route.insert(0, tree.vertex(edge.fromVertex()).point())
idxEnd = edge.fromVertex()
# Display
rb = QgsRubberBand(iface.mapCanvas())
rb.setColor(Qt.green)
# This may require coordinate transformation if project's CRS
# is different than layer's CRS
for p in route:
rb.addPoint(p)