QGISで行う経路検索について紹介します。
QGISで経路検索を行うに当って、qgis.networkanalysisの使いします。
QGISで行わず、postgreSQLのpgroutingに任せる方法もあります。
1.networkanalysisを使い、経路検索に使用するツリーを作成します。
index = route_layer.fieldNameIndex(u'route')
director = nk.QgsLineVectorLayerDirector(route_layer, index, '1', '-1', '0', 1)
# route_layer 経路検索に使用するラインレイヤ
# index 経路検索の種類を指定するフィールドのインデックス -1の場合 使用しない
# 順方向の値 例: "1"
# 逆方向の値 例:"-1"
# 双方向 例: "0"
# デフォルトの方向性 例: "1" 単方向
properter = nk.QgsDistanceArcProperter()
director.addProperter(properter)
crs = self.iface.mapCanvas().mapRenderer().destinationCrs()
builder = nk.QgsGraphBuilder(crs, topologyTolerance=0.00000005)
# 座標系、ライン間の接続誤差を指定
tied_points = director.makeGraph(builder, points)
# builder と ラインに追加するポイントリスト
route_graph = builder.graph()
2.検索する経路の始点と終点を指定して、経路検索を実行します。
start = QgsPoint() # 経路の始点
stop = QgsPoint() # 経路の終点
tied_start_index = points.index(start)
tied_stop_index = points.index(stop)
tstart = tied_points[tied_start_index]
tstop = tied_points[tied_stop_index]
# area
idstart = graph.findVertex(tstart)
idstop = graph.findVertex(tstop)
tree, cost = nk.QgsGraphAnalyzer.dijkstra(graph, idstart, 0)
# 経路検索の結果
length = cost[idstop]
# 経路検索の中から、終点までの距離を取得
point_list = []
if tree[idstop] == -1:
# 経路発見できず
length = 0
return length, [tstop, tstart]
else:
# 経路を発見
# 終点から辿っていき、ラインを形成するポイントをリストに格納する
current_point = idstop
while current_point != idstart:
arc_index = tree[current_point]
# ツリーからポイントがあるラインのインデックスを取得
arc = graph.arc(arc_index)
# グラフからラインを取得
in_vertex_index = arc.inVertex()
# ラインの始点のインデックスを取得
# 終点の場合はarc.outVertex()
vertex = graph.vertex(in_vertex_index)
# グラフから点を取得
point = vertex.point()
point_list.append(point)
current_point = graph.arc(tree[current_point]).outVertex()
point_list.append(tstart)
return length, point_list