Skip to content

Instantly share code, notes, and snippets.

@ghtmtt
Created July 8, 2021 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghtmtt/bc183f0a627d38840f90ad453ba18593 to your computer and use it in GitHub Desktop.
Save ghtmtt/bc183f0a627d38840f90ad453ba18593 to your computer and use it in GitHub Desktop.
qgis_network_analysis
project = QgsProject.instance()
start_points = project.mapLayersByName('start_points')[0] # start
end_points = project.mapLayersByName('end_points')[0] # end
network = project.mapLayersByName('network')[0] # network
## from polyline to director
director = QgsVectorLayerDirector(
source=network,
directionFieldId=-1,
directDirectionValue='',
reverseDirectionValue='',
bothDirectionValue='',
defaultDirection=0 # only forward
)
# adding the strategy
strategy = QgsNetworkDistanceStrategy()
director.addStrategy(strategy)
# initialzie the graph builder (no snap at all)
builder = QgsGraphBuilder(
network.crs(),
True,
0
)
# loop on the start point features
for i in start_points.getFeatures():
igeom = i.geometry()
# get the geometry as QgsPointXY
start_point = igeom.asPoint()
# loop on the end point faetures
for k in end_points.getFeatures():
# get the geometry as QgsPointXY
kgeom = k.geometry()
end_point = kgeom.asPoint()
# here QGIS explodes !
tiedPoints = director.makeGraph(builder, [start_point, end_point])
graph = builder.graph()
idxStart = graph.findVertex(tiedPoints[0])
idxEnd = graph.findVertex(tiedPoints[1])
(tree, costs) = QgsGraphAnalyzer.dijkstra(graph, idxStart, 0)
if idxEnd != -1:
cost = costs[idxEnd]
print(cost)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment