Routing on the Web

From GeoBox

Jump to: navigation, search

We already see how to create a network (graph) from the OSM data.

In this example, we will provide such service (routing service) on the web.

How it works

The routing service is provided by the database.


Testing

Go to http://localhost/~geobox/pgrouting/.

routing-0.html is just a basic example, using both OpenLayers and GeoExt to provide a map interface over OSM tiles. The tiles showed are images already rendered on the server side.

routing-final.html is the complete (yet very simple) interface to the routing service. In this interface, you can click twice, to define the start and ending points.

Starting and ending point are the parameters passed to the route calculation, as long as the desired routing algorithm. Since we are using two different coordinate systems, some transformation is necessary.

			// transform the two geometries from EPSG:900913 to EPSG:4326
			var startpoint = layer.features[0].geometry.clone();
			startpoint.transform(epsg_900913, epsg_4326);
			var finalpoint = layer.features[1].geometry.clone();
			finalpoint.transform(epsg_900913, epsg_4326);

The route is computed on the server side, using /php/pgrouting.php. This script return a JSON data structure, containing all segments selected between start and end point.

The returned data is then rendered on top of the existing map.

Note: you need a JSON viewer plugin. Install it from [1]

http://localhost/~geobox/pgrouting/php/pgrouting.php?startpoint=-8.4305975443412%2041.545902592022&finalpoint=-8.3811590677808%2041.568253481957&method=SPD

The algorithm used inside the PHP script is quite simple:

  • For each point (using $lonlat[0] and $lonlat[1]), one node in selected from its neighborhood.
      $sql = "SELECT gid, source, target, the_geom, 
		          distance(the_geom, GeometryFromText(
	                   'POINT(".$lonlat[0]." ".$lonlat[1].")', 4326)) AS dist 
	             FROM ".TABLE."  
	             WHERE the_geom && setsrid(
	                   'BOX3D(".($lonlat[0]-0.1)." 
	                          ".($lonlat[1]-0.1).", 
	                          ".($lonlat[0]+0.1)." 
	                          ".($lonlat[1]+0.1).")'::box3d, 4326) 
	             ORDER BY dist LIMIT 1";
  • After discovering the start and end nodes, another query is sent to the database:
        $sql = "SELECT rt.gid, ST_AsGeoJSON(rt.the_geom) AS geojson, 
	                 length(rt.the_geom) AS length, ".TABLE.".gid 
	              FROM ".TABLE.", 
	                  (SELECT gid, the_geom 
	                      FROM dijkstra_sp_delta(
	                          '".TABLE."',
	                          ".$startEdge['source'].",
	                          ".$endEdge['target'].",
	                          0.1)
	                   ) as rt 
	              WHERE ".TABLE.".gid=rt.gid;";
Personal tools