[OpenLayers-Users] openlayers & postgis & pgrouting through a script

Edel Banks osgisfyp at gmail.com
Tue Mar 11 15:41:12 EDT 2008


Hi All,

I have just recently started using openlayers and think it is great.

I have set up a map with several postgis layers in it using geoserver and
openlayers. Now I would like to add a dynamic routing layer to the map using
a user entered start and end point.  I followed the pgrouting example for
doing this with openlayers on the pgrouting website but when it the
calculate route button is pressed nothing happens. Im not sure if the
ax_routing.php file is being run.  It is in the same directory as the html
file.


Openlayers code:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <style type="text/css">
        #map {
            width: 500px;
            height: 312px;
            border: 1px solid black;
        }
    </style>
    <script src="./OpenLayers-google/lib/OpenLayers.js"></script>
    <script type="text/javascript">


        var SinglePoint = OpenLayers.Class.create();
        SinglePoint.prototype = OpenLayers.Class.inherit(
OpenLayers.Handler.Point, {
            createFeature: function(evt) {
                this.control.layer.removeFeatures(
this.control.layer.features);
                OpenLayers.Handler.Point.prototype.createFeature.apply(this,
arguments);
            }
        });

        var start_style = OpenLayers.Util.applyDefaults({
            externalGraphic: "start.png",
            graphicWidth: 18,
            graphicHeight: 26,
            graphicYOffset: -26,
            graphicOpacity: 1
        }, OpenLayers.Feature.Vector.style['default']);

        var stop_style = OpenLayers.Util.applyDefaults({
            externalGraphic: "stop.png",
            graphicWidth: 18,
            graphicHeight: 26,
            graphicYOffset: -26,
            graphicOpacity: 1
        }, OpenLayers.Feature.Vector.style['default']);

         var result_style = OpenLayers.Util.applyDefaults({
             strokeWidth: 3,
             strokeColor: "#ff0000",
             fillOpacity: 0
         }, OpenLayers.Feature.Vector.style['default']);



        // global variables
        var map, parser, start, stop, downtown, result, controls;

        function init() {
            var bounds = new OpenLayers.Bounds(

                305097.5401555448, 226935.368699667,        // left, bottom
                318253.033844963, 237653.04983245343        // right, top

            );


            var options = {
                controls: [],
                maxExtent: bounds,
                maxResolution: 39.6698972242898,
                projection: "EPSG:29900",
                units: 'm'
            };


            map = new OpenLayers.Map('map', options);




            // create and add layers to the map
            var satellite = new OpenLayers.Layer.WMS(
                "pedestrianRouteFinder:required_roads - Untiled", "
http://localhost:8080/geoserver/wms",
                {
                    height: '652',
                    width: '800',
                    layers: 'pedestrianRouteFinder:required_roads',
                    styles: 'required_roads_style',
                    srs: 'EPSG:29900',
                    format: 'image/png'
                },
                {isBaseLayer:true},
                {singleTile: true}
            );


            start = new OpenLayers.Layer.Vector("Start point", { style:
start_style });
            stop = new OpenLayers.Layer.Vector("End point", {style:
stop_style});



            map.addLayers([satellite, start, stop]);
            downtown = new OpenLayers.Layer.Vector("Downtown data area",
                                                 {style: result_style});
            result = new OpenLayers.Layer.Vector("Routing results",
                                                 {style: result_style});

            map.addLayers([satellite, start, stop, downtown, result]); //

            // create a feature from a wkt string and add it to the map
            parser = new OpenLayers.Format.WKT();

            var wkt = "POLYGON((310097.5401555448  237653.04983245343,
310097.5401555448 226935.368699667, 318253.033844963 226935.368699667,
318253.033844963 237653.04983245343, 310097.5401555448 237653.04983245343
))";
      //      var wkt = "POLYGON((-13737893 6151394,
      //                          -13737893 6141906,
                            //      -13728396 6141906,
                            //      -13728396 6151394,
                            //      -13737893 6151394))";



                                //-13737893, 6141906, -13728396, 6151394



            var geometry = parser.read(wkt);
            var feature = new OpenLayers.Feature.Vector(geometry);
            downtown.addFeatures([feature]);


            // set default position
            map.zoomToExtent(bounds);

            // controls
            controls = {
              start: new OpenLayers.Control.DrawFeature(start, SinglePoint),
              stop: new OpenLayers.Control.DrawFeature(stop, SinglePoint)
            }
            for (var key in controls) {
                map.addControl(controls[key]);
            }



            map.addControl(new OpenLayers.Control.PanZoomBar());
            map.addControl(new OpenLayers.Control.Navigation());
            map.addControl(new OpenLayers.Control.MousePosition({element:
$('location')}));
            map.addControl(new OpenLayers.Control.LayerSwitcher());


        } // end init

        function toggleControl(element) {
            for (key in controls) {
                if (element.value == key && element.checked) {
                    controls[key].activate();
                } else {
                    controls[key].deactivate();
                }
            }
        }

        function compute() {
            var startPoint = start.features[0];
            var stopPoint = stop.features[0];

            if (startPoint && stopPoint) {
                var result = {
                    startpoint: startPoint.geometry.x + ' ' +
startPoint.geometry.y,
                    finalpoint: stopPoint.geometry.x + ' ' +
stopPoint.geometry.y,
                    method: OpenLayers.Util.getElement('method').value,
                    region: "downtown",
                    srid: "29900"
                };

                OpenLayers.loadURL("./ax_routing.php",
                                   OpenLayers.Util.getParameterString
(result),
                                   null,
                                   displayRoute);
            }
        }

        function displayRoute(response) {
            if (response && response.responseXML) {
                // erase the previous results
                result.removeFeatures(result.features);

                // parse the features
                var edges = response.responseXML.getElementsByTagName
('edge');
                var features = [];
                for (var i = 0; i < edges.length; i++) {
                    var g = parser.read
(edges[i].getElementsByTagName('wkt')[0].textContent);
                    features.push(new OpenLayers.Feature.Vector(g));
                }
                result.addFeatures(features);
            }
        }

    </script>
  </head>
  <body onload="init()">
    <div id="map"></div>

    <ul>
      <li>
        <input type="radio" name="control" id="noneToggle"
               onclick="toggleControl(this);" checked="checked" />
        <label for="noneToggle">navigate</label>
      </li>
      <li>
        <input type="radio" name="control" value="start" id="startToggle"
               onclick="toggleControl(this);" />
        <label for="startToggle">set start point</label>
      </li>
      <li>
        <input type="radio" name="control" value="stop" id="stopToggle"
               onclick="toggleControl(this);" />
        <label for="stopToggle">set stop point</label>
      </li>
    </ul>

    <select id="method">
      <option value="SPD">Shortest Path Dijkstra - undirected
(BBox)</option>
      <option value="SPA">Shortest Path A Star - undirected</option>
      <option value="SPS">Shortest Path Shooting Star</option>
    </select>
    <button onclick="compute()">Calculate Route</button>

  </body>
</html>


ax_routing.php code:

<?php



  // Database connection settings
  define("PG_DB"  , "pedestrianRouteFinder");
  define("PG_HOST", "localhost");
  define("PG_USER", "fyp");
  define("PG_PSWD", "postgres");
  define("PG_PORT", "5432");
  define("TABLE",   "required_roads");

  $counter = $pathlength = 0;

  // Retrieve start point
  $start = split(' ',$_REQUEST['startpoint']);
  $startPoint = array($start[0], $start[1]);

  // Retrieve end point
  $end = split(' ',$_REQUEST['finalpoint']);
  $endPoint = array($end[0], $end[1]);

  // Find the nearest edge
  $startEdge = findNearestEdge($startPoint);
  $endEdge   = findNearestEdge($endPoint);

  // FUNCTION findNearestEdge
  function findNearestEdge($lonlat) {

    // Connect to database
    $con = pg_connect("dbname=".PG_DB." host=".PG_HOST." user=".PG_USER."
password=".PG_PSWD);

    $sql = "SELECT gid, source, target, the_geom,
             distance(the_geom, GeometryFromText(
                  'POINT(".$lonlat[0]." ".$lonlat[1].")', 54004)) AS dist
            FROM ".TABLE."
            WHERE the_geom && setsrid(
                  'BOX3D(".($lonlat[0]-200)."
                         ".($lonlat[1]-200).",
                         ".($lonlat[0]+200)."
                         ".($lonlat[1]+200).")'::box3d, 54004)
            ORDER BY dist LIMIT 1";

    $query = pg_query($con,$sql);

    $edge['gid']      = pg_fetch_result($query, 0, 0);
    $edge['source']   = pg_fetch_result($query, 0, 1);
    $edge['target']   = pg_fetch_result($query, 0, 2);
    $edge['the_geom'] = pg_fetch_result($query, 0, 3);

    // Close database connection
    pg_close($con);

    return $edge;
  }

  // Select the routing algorithm
  switch($_REQUEST['method']) {

    case 'SPD' : // Shortest Path Dijkstra

      $sql = "SELECT rt.gid, AsText(rt.the_geom) AS wkt,
                   length(rt.the_geom) AS length, ".TABLE.".id
                FROM ".TABLE.",
                    (SELECT gid, the_geom
                        FROM dijkstra_sp_delta(
                            '".TABLE."',
                            ".$startEdge['source'].",
                            ".$endEdge['target'].",
                            3000)
                     ) as rt
                WHERE ".TABLE.".gid=rt.gid;";
      break;

    case 'SPA' : // Shortest Path A*

      $sql = "SELECT rt.gid, AsText(rt.the_geom) AS wkt,
                     length(rt.the_geom) AS length, ".TABLE.".id
                  FROM ".TABLE.",
                      (SELECT gid, the_geom
                          FROM astar_sp_delta(
                              '".TABLE."',
                              ".$startEdge['source'].",
                              ".$endEdge['target'].",
                              3000)
                       ) as rt
                  WHERE ".TABLE.".gid=rt.gid;";
      break;

    case 'SPS' : // Shortest Path Shooting*

      $sql = "SELECT rt.gid, AsText(rt.the_geom) AS wkt,
                     length(rt.the_geom) AS length, ".TABLE.".id
                  FROM ".TABLE.",
                      (SELECT gid, the_geom
                          FROM shootingstar_sp(
                              '".TABLE."',
                              ".$startEdge['gid'].",
                              ".$endEdge['gid'].",
                              3000, 'length', false, false)
                       ) as rt
                  WHERE ".TABLE.".gid=rt.gid;";
      break;

  } // close switch

  // Database connection and query
  $dbcon = pg_connect("dbname=".PG_DB." host=".PG_HOST." user=".PG_USER);

  $query = pg_query($dbcon,$sql);

  // Return route as XML
  $xml  = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'."\n";
  $xml .= "<route>\n";

  // Add edges to XML file
  while($edge=pg_fetch_assoc($query)) {

    $pathlength += $edge['length'];

    $xml .= "\t<edge id='".++$counter."'>\n";
    $xml .= "\t\t<id>".$edge['id']."</id>\n";
    $xml .= "\t\t<wkt>".$edge['wkt']."</wkt>\n";
    $xml .= "\t\t<length>".round(($pathlength/1000),3)."</length>\n";
    $xml .= "\t</edge>\n";
  }

  $xml .= "</route>\n";

  // Close database connection
  pg_close($dbcon);

  // Return routing result
  header('Content-type: text/xml',true);
  echo $xml;

?>


I have the latest php installed at c:\PHP\, and added to the path variable.
Anybody point me in the right direction?

Thanks
osgis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/openlayers-users/attachments/20080311/b85f617c/attachment.html


More information about the Users mailing list