geotools的最短路徑實現


Geotools提供了一個Graph的擴展包,使用它可以實現最短路徑的查找,提供的算法有Dijkstra和AStarApi的功能非常強大,只需要提供linefeatures對象,即可創建graph,然后調用算法即可實現最短路徑查找,權重可以自由設置,對於不懂算法的人用起來也毫不費力。

Dijkstra的使用

String filePath = "E:\\gis資料\\測試數據\\道路中心線.shp";
//讀取shp數據
DataStore dataStore = readShapeFile(filePath);
SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
SimpleFeatureCollection simFeatureCollect =featureSource.getFeatures();

final Integer num = new Integer(0);
System.out.println("shp文件原始線的個數:" + simFeatureCollect.size());

 

//創建graph數據結構
Graph graph = buildGraph(simFeatureCollect);

 

//這里是定義權重

DijkstraIterator.EdgeWeighter weighter = new DijkstraIterator.EdgeWeighter(){
    @Override
    public double getWeight(Edge edge) {

//這個方法返回的值就是權重,這里使用的最簡單的線的長度

//如果有路況、限速等信息,可以做的更復雜一些
        SimpleFeature feature = (SimpleFeature)edge.getObject();
        Geometry geometry = (Geometry)feature.getDefaultGeometry();

        return geometry.getLength();
    }
};
Date startT = new Date();

//初始化查找器
DijkstraShortestPathFinder pf = new DijkstraShortestPathFinder(graph,start,weighter);
pf.calculate();

//傳入終點,得到最短路徑
Path path = pf.getPath(destination);
Date end = new Date();
System.out.println("迪傑斯特拉算法耗時:" +(end.getTime() - startT.getTime()));
System.out.println("迪傑斯特拉算法距離:"+getPathLength(path));
System.out.println(destination.getID()+""+start.equals(destination));

 

 

//AStar算法

public static void AStarShortestPath(Graph graph,Node startNode,Node endNode){
    AStarIterator.AStarFunctions aStarFunction = new  AStarIterator.AStarFunctions(endNode){
        @Override
        public double cost(AStarIterator.AStarNode aStarNode, AStarIterator.AStarNode aStarNode1) {
           Edge edge = aStarNode.getNode().getEdge(aStarNode1.getNode());
            SimpleFeature feature = (SimpleFeature)edge.getObject();
            Geometry geometry = (Geometry)feature.getDefaultGeometry();
            //System.out.println(aStarNode.getH());
            return geometry.getLength();
        }

        @Override
        public double h(Node node) {
            return -10;
        }
    };
    Date start = new Date();
    AStarShortestPathFinder aStarPf = new AStarShortestPathFinder(graph,startNode,endNode,aStarFunction);
    try {
        aStarPf.calculate();
        Date end = new Date();
        System.out.println("AStar算法耗時:" +(end.getTime() - start.getTime()));
        System.out.println("AStar算法距離:" + getPathLength(aStarPf.getPath()));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

 

 

 

AStar算法使用也很簡單,可參考api使用文檔。兩個算法效率比較下來,AStar算法效率更好。算法驗證和效率比較:

使用同樣的起點和終點,分別調用上面兩個算法,計算結果如下:

shp文件原始線段的個數:67749

AStar算法耗時:84ms

AStar距離:0.2307215100346536

迪傑斯特拉耗時:188ms

迪傑斯特拉距離:0.2307215100346536


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM