Geotools提供了一个Graph的扩展包,使用它可以实现最短路径的查找,提供的算法有和AStar。Api的功能非常强大,只需要提供line的features对象,即可创建graph, 然后调用算法即可实现最短路径查找,权重可以自由设置,对于不懂算法的人用起来也毫不费力的使用。
String filePath = "E:\\gis资料|\测试数据\\道路中心线.shp";
//读取shp数据
DataStore dataStore = readShapeFile (filePath);
SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getTypeNames0[0]);
SimpleFeatureCollection simFeatureCollect =featureSource.getFeatures();
final Integer num = new Integer(0);
System.out.printn("shp文件原始线的个数: " + simFeatureCollect.size();
//创建graph数据结构
Graph graph = buildGraph (simFeatureCollect);
//这里是定义权重
Dijkstralterator .EdgeWeighter weighter = new Djkstralterator .EdgeWeighter({
@Override
public double getWeight(Edge edge) {
//这个方法返回的值就是权重,这里使用的最简单的线的长度
//如果有路况、限速等信息,可以做的更复杂- -些
SimpleFeature feature = (SimpleFeature)edge.getObject();
Geometry geometry = (Geometry)feature.getDefaultGeometry(;
return geometry.getL .ength();
Date startT = new Date();
//初始化查找器
DijkstraShortestPathFinder pf = new DjkstraShortestPathFinder(graph,start,weighter);
pf.calculate();
//传入终点,得到最短路径
Path path = pf.getPath(destination);
Date end = new Date();
System.out. printIn("迪杰斯特拉算法耗时: " +(end.getTime() - startT.getTime());
System.out. println("迪杰斯特拉算法距离: "+getPathL ength (path);
System.out. printIn(destination.getID(0+"+start.equals(destination));
//AStar算法
public static void AStarShortestPath(Graph graph,Node startNode,Node endNode){
AStarlterator .AStarFunctions aStarFunction = new AStarlterator .AStarFunctions(endNode){
@Override
public double cost(AStarlterator.AStarNode aStarNode, AStarlterator.AStarNode aStarNode1) {
Edge edge = aStarNode.getNode0.getEdge(aStarNode 1.getNode();
SimpleFeature feature = (SimpleFeature)edge.getObject);
Geometry geometry = (Geometry)feature.getDefaultGeometry();
//System.out.printIn(aStarNode.getH0);
return geometry.getL ength();
@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算法距离: " + getPathL .ength(aStarPf.getPath0));
. } catch (Exceptione) {
e.printStackTrace();
}
AStar算法使用也很简单,可参考api使用文档。 两个算法效率比较下来,AStar算法效率更好。 算法验证和效率比较:
使用同样的起点和终点,分别调用上面两个算法,计算结果如下:
shp文件原始线段的个数: 67749
AStar算法耗时: 84ms
@
AStar距离: 0.2307215100346536
迪杰斯特拉耗时: 188ms
迪杰斯特拉距离: 0.2307215100346536 .
参考:https://wenku.baidu.com/view/f7f72108b7daa58da0116c175f0e7cd1842518aa.html
创建Graph方向图:https://www.cnblogs.com/help-silence/p/11872194.html(Geotools中读取shapefile路网数据,并创建DirectedGraph)
官方文档:https://docs.geotools.org/latest/userguide/extension/graph/