[GIS] Create routing graph (as software objects) from roads Shapefile using pgRouting

geotoolspgroutingpythonroutingshapefile

Intro: It's easy with OSM XML to run my software algorithm converting the XML to my custom software objects representing routing graph: You have ways with easy links to the (ordered) nodes constructing the segment with lat/lon.

Problem: Usually one starts with data as Shapefile, so the easy solution is to use Shape->OSM converter. I want to work directly with the Shapefiles.

Question: It's easy to import Shapefile to PostgreSql and using PostGis to query bounding boxes of the coverage based on geospatial logic. The next step is to use pgRouting in order to parse the raw Shapefile data (roads) to software objects representing the routing graph, for example in Java something like:

class Node() {
    double lat;
    double lon;
    int nodeId;
}

class Segment() {
    LinkedList byOrderNodes;  //of type class Node above
    int segmentId;
    boolean oneWay;
}

class graph() {
    ArrayList segments;  //of type Segment above
}

How to achieve this with pgRouting – What queries and functions to use?

Note – I don't mind between Python/Java/etc.

Best Answer

For pgRouting, use pgr_CreateTopology function. http://docs.pgrouting.org/2.3/en/src/topology/doc/pgr_createTopology.html#pgr-create-topology

Basic steps:

1) Load your shapefile into PostgreSQL/PostGIS with shp2pgsql or shp2pgsql-gui or ogr2ogr or any other tool like QGIS

2) Add two columns to the table source / target

ALTER TABLE your_table ADD COLUMN "source" integer;
ALTER TABLE your_table ADD COLUMN "target" integer;

3)

SELECT pgr_createTopology('your_table', 0.00001, 'geom', 'gid');

gid may be different depending on which tool you used to load the shapefile, but should be integer that is unique for the table.

0.00001 is the tolerance at which two nodes are considered the same. This will vary depending on projection of your data. For example for a meter projection,you may want to make this higher like 0.5 (1/2 meter)

The function will populate the source and target fields with nodes ids and also create a table your_table_vertices_pgr which is basically like your Node table.

From there use the pgRouting routing functions.

This and many other topics are covered in our book currently in draft form - http://locatepress.com/pgrouting