使用pgRouting进行路径分析

pgRouting是一个基于Postgresql/PostGIS的项目,目的是提供路径分析的功能,它是PostLBS的一个子项目,这个项目使用GPL许可发布。

pgRouting的安装很简单,以Windows为例,下载编译包以后解压缩,将lib目录下文件复制到Postgresql的lib目录下,再在Postgresql数据库中执行share/contrib目录下的sql脚本,这些脚本分别对应不同的功能:“core”对应Dijkstra算法计算最短路径,使用函数为“shortest_path_*”;“dd”对应Driving distance行驶距离计算,使用函数为“driving_distance”;“tps”对应采用遗传算法的Travelling Sales Person方法,使用函数为“tsp_*”。

下面用日本神奈川的城市道路数据进行测试。

计算最短路径我们使用shortest_path这个函数,这个函数需要提供5个参数,下面是shortest_path的函数原型:
shortest_path(sql text,source_id integer,target_id integer,directed boolean,has_reverse_cost boolean)

这里的sql一个sql语句,通过这个sql语句可以获得需要计算的数据集合;source和target分别是起始节点的id;directed表明是否限制方向。需要说明的是这个sql语句,在这sql中需要查询到一些特殊的字段:id、source、target、cost等,而且这些字段的类型必须和pgRouting的要求相符。下面是我构造的一个查询
SELECT * FROM shortest_path(' SELECT objectid as id, source::integer, target::integer, length::double precision as cost FROM kanagawa', 84808,13234,false,false);

在本机上测试,上述查询在19万行数据中执行了2秒得到结果318行(路径分为318段):

以下是服务器端的主要代码
public ArrayList> getNodes(int source,int target) { ArrayList> result = new ArrayList>(); if ( this.getConn()==null ) return result; try { String sql = "SELECT * FROM shortest_path('SELECT objectid as id,source::integer,target::integer,length::double precision as cost FROM kanagawa',"+source+","+target+",false) as a left join kanagawa as b on a.edge_id=b.objectid;"; Statement st = this.getConn().createStatement(); st.setFetchSize(0); ResultSet rs = st.executeQuery(sql); while (rs.next()) { HashMap map = new HashMap(); map.put("x1",rs.getDouble("x1")); map.put("y1",rs.getDouble("y1")); map.put("x2",rs.getDouble("x2")); map.put("y2",rs.getDouble("y2")); result.add(map); } rs.close(); st.close(); } catch(Exception e) { System.err.print(e); } return result; }

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...