2009年5月4日星期一

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

1 条评论:

IceSniper 说...

你好,我初学PostgreSQL做项目,想用它建立空间数据库,但我对GIS方面不太了解,不知道如何建库,能不能帮帮忙介绍一下?谢谢!