微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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; }

原文地址:https://www.jb51.cc/postgresql/197260.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐