1、头文件
#include <qgsvectorlayerdirector.h>
#include <qgsgraphbuilder.h>
#include <qgsgraph.h>
#include <qgsgraphanalyzer.h>
#include <qgsvectorlayerdirector.h>
#include <qgsnetworkdistancestrategy.h>
2、需要用于路径规划的变量
QgsFeatureSource* mNetwork; //路网图层
QgsVectorLayerDirector *mDirector = nullptr;
std::unique_ptr< QgsGraphBuilder > mBuilder;
std::unique_ptr< QgsGraph > mGraph;
3、代码实现
mNetwork = roadLayer; //路网矢量图层
mDirector = new QgsVectorLayerDirector(mNetwork, -1, "", "", "", QgsVectorLayerDirector::DirectionBoth);
QVector< QgsPointXY > points;
QVector< QgsPointXY > snappedPoints;
QgsPointXY startPt(123.0, 20.1);
QgsPointXY endPt(123.1, 20.2);
points << startPt << endPt;
mDirector->addStrategy(new QgsNetworkDistanceStrategy());
mBuilder = qgis::make_unique< QgsGraphBuilder >(mNetwork->sourceCrs(), true, 0.0);
mDirector->makeGraph(mBuilder.get(), points, snappedPoints);
QgsGraph *graph = mBuilder->graph();
int idxStart = graph->findVertex(snappedPoints[0]);
int idxEnd = graph->findVertex(snappedPoints[1]);
QVector< int > tree;
QVector< double > costs;
QgsGraphAnalyzer::dijkstra(graph, idxStart, 0, &tree, &costs);
if (tree.at(idxEnd) == -1)
{
throw QgsProcessingException(QObject::tr("There is no route from start point to end point."));
}
QgsPolyline route;
route.append(QgsPoint(graph->vertex(idxEnd).point()));
while (idxEnd != idxStart)
{
idxEnd = graph->edge(tree.at(idxEnd)).fromVertex();
route.append(QgsPoint(graph->vertex(idxEnd).point()));
}
QgsGeometry geom = QgsGeometry::fromPolyline(route); //生成规划后的最短路径线几何对象
得到这个几何对象后,就可以在地图上显示了。
4、存在的问题
路径规划的效率较低,通过QGIS桌面端也是这个效率,所以,应该没有优化的空间了,如果想得到效率高的路径规划功能,就需要自己写或者用开源的pgrounting。
后续准备试试pgrounting,敬请期待!