1

I'm new to all this I'm still trying to understand how things work. I have found a tutorial for pgrouting that shows the shortest path with Dijsktra or A* or shooting star at a map .

I followed the tutorial but I couldn't set it to run . The tutorial is this ! I have written some code and but I can't understand why it doesn't work ! my PHP code seems to work correct(if i test it alone) it gives me the result I want , but i don't know if it can communicate properly with my HTML ! if someone could give a look at the code and point me were I wrong(with as much detail as possible because I'm new) I would appreciate it

NOTICE : in order of some of my code to be shown I erased the " < " from the HTML code line 1 - 22 and at PHP code I erased the " " from the start end ending of the file

HTML code:

<pre>

html xmlns="http://www.w3.org/1999/xhtml">
    head>
        title>OpenLayers Take Points Example</title>
            <style type="text/css">
                 html, body, #map {
                margin: 0;
                width: 99.5%;
                height: 90%;
            }
        </style>

script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
script type="text/javascript" src="ext/ext-all.js"></script>
link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css" />
link rel="stylesheet" type="text/css" href="ext/examples/shared/examples.css" />
script src="OpLayer/lib/OpenLayers.js" type="text/javascript"></script>
script type="text/javascript" src="GeoExt/lib/GeoExt.js"></script>
link rel="stylesheet" href="OpLayer/theme/default/google.css" type="text/css">
script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAl9RMqSzhPUXAfeBCXOussRTQDbvAygy0cfGJr8dEMAYKf3RWNBQqP9mjKIsqTfmAlz5LOJ3Xpy5s4w'></script>
script src="DrawPoints.js" type="text/javascript"></script>
script type="text/javascript">

var array = new Array();
var count = 0;
    OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
                defaultHandlerOptions: {
                    'single': true,
                    'double': false,
                    'pixelTolerance': 0,
                    'stopSingle': false,
                    'stopDouble': false
                },

                initialize: function(options) {
                    this.handlerOptions = OpenLayers.Util.extend(
                        {}, this.defaultHandlerOptions
                    );
                    OpenLayers.Control.prototype.initialize.apply(
                        this, arguments
                    ); 
                    this.handler = new OpenLayers.Handler.Click(
                        this, {
                            'click': this.trigger
                        }, this.handlerOptions
                    );
                }, 

                trigger: function(e) {

                   var xy = map.getLonLatFromViewPortPx(e.xy);
           array[count++] = xy.transform(epsg_900913, epsg_4326);

            if(count==2){alert("is "+count);
                executeSQL(array);
            }
                }

            });


            var map,json_layer,myStyles,undifined;
        var epsg_4326 = new OpenLayers.Projection("EPSG:4326");
            var epsg_900913 = new OpenLayers.Projection("EPSG:900913");     


function init(){

    var options = {
            projection: epsg_900913,
            displayProjection: epsg_4326,
            units: "m",
            numZoomLevels: 20,
            maxResolution: 156543.0339,
            maxExtent: new OpenLayers.Bounds(-20037508, -20037508,  20037508, 20037508)
              };

                map = new OpenLayers.Map('map', options);
                var google_street = new OpenLayers.Layer.Google("Google Streets",{'sphericalMercator': true, numZoomLevels: 20} );

                var google_satellite = new OpenLayers.Layer.Google("Google Satellite",
            {type: G_SATELLITE_MAP, 'sphericalMercator': true, numZoomLevels: 20}  );

         var points_layer = new OpenLayers.Layer.Vector("points");
             var draw_points = new DrawPoints(points_layer);
                 var drag_points = new OpenLayers.Control.DragFeature(points_layer, {
                    autoActivate: true
             });
        drag_points.onComplete = function() {
            route.destroyFeatures();
        };


                 map.addControls([draw_points, drag_points]);


        myStyles = new OpenLayers.StyleMap({
                "default":new OpenLayers.Style({
                    fillColor: "#ffcc66",
                    strokeColor: "#ff9933",
                    strokeWidth: 3}),
                "select": new OpenLayers.Style({
                    fillColor :"#66ccff",
                    strokeColor :"3399ff"})
        });

                map.addLayers([google_street , google_satellite]);
                map.addControl(new OpenLayers.Control.LayerSwitcher());
        map.addControl(new OpenLayers.Control.MousePosition());
        map.addControl(new OpenLayers.Control.Navigation());
                map.addControl(new OpenLayers.Control.PanZoomBar());
                map.addControl(new OpenLayers.Control.ScaleLine());
                //map.addControl( new OpenLayers.Control.Permalink('permalink'));
                map.addControl( new OpenLayers.Control.OverviewMap());
                map.addControl(new OpenLayers.Control.KeyboardDefaults());

        //somewhere in athens
        var map_center = new OpenLayers.LonLat(23.723022460938,37.956298828125); 

        //metatropi apo x/y se spherical          
        map_center.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()); 
        map.setCenter(map_center, 17); 

                var click = new OpenLayers.Control.Click();
                map.addControl(click);
                click.activate();


            }


    var format = new OpenLayers.Format.GeoJSON({
                internalProjection: epsg_900913,
                            externalProjection: epsg_4326});

function executeSQL(xy){
    var json_url = "http://localhost/Geoext/pgrouting1.php?";
    json_url += "x1=" + escape(array[0].lon);
    json_url += "&y1=" + escape(array[0].lat);
    json_url += "&x2=" + escape(array[1].lon);
    json_url += "&y2=" + escape(array[1].lat);
    json_url += "&method=SPD"; 
    alert(json_url);
    if(undifined != json_layer){
        json_layer.destroy();
    }

    json_layer = new OpenLayers.Layer.Vector("Route",
                    {styleMap: myStyles,
                         strategies: [new OpenLayers.Strategy.Fixed()],
                     protocol: new OpenLayers.Protocol.HTTP({
                     url:json_url,
                     format: format})
           });

    map.addLayer(json_layer);

};

        </script>
    </head>
    <body onload="init()">
        <h1 id="title">Add markers example</h1>

        <div id="tags">
        </div>

        <p id="shortdesc">
            An example .

        </p>

        <div id="map" class="smallmap"></div>
    </body>
</html>
</code>

and my php code :

//$a =$_SERVER["REMOTE_ADDR"];
//echo" $a ";
   // Database connection settings
   define("PG_DB"  , "athens");
   define("PG_HOST", "localhost"); 
   define("PG_USER", "postgres");
   define("PG_PORT", "5432"); 
   define("TABLE",   "ways");

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

    if($con == true){
        echo "Connection succeded\n";
    }else{
        echo "Connection couldn't established\n";
    } 

$x1 = $_GET["x1"]; 
$y1 = $_GET["y1"];
$x2 = $_GET["x2"]; 
$y2 = $_GET["y2"];
$method = $_GET["method"]; 

echo "to x1 einai toso $x1 --y1 $y1 ---x2 $x2 -- y2 $y2 method $method\n";


   // Find the nearest edge
   $startEdge = findNearestEdge($x1,$y1);
   $endEdge   = findNearestEdge($x2,$y2);
echo"$startEdge kaiiiiiiiiiiiiiiiii $endEdge ";
   // FUNCTION findNearestEdge
   function findNearestEdge($a , $b) {

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

      $sql = "SELECT gid, source, target, the_geom, 
                  distance(the_geom, GeometryFromText(
                       'POINT(".$a." ".$b.")', 4326)) AS dist 
                 FROM ".TABLE."  
                 WHERE the_geom && setsrid(
                       'BOX3D(".($a-0.1)." 
                              ".($b-0.1).", 
                              ".($a+0.1)." 
                              ".($b+0.1).")'::box3d, 4326) 
                 ORDER BY dist LIMIT 1";

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

      $ed[0]=$edge['gid']      = pg_fetch_result($query, 0, 0);  
      $ed[1]=$edge['source']   = pg_fetch_result($query, 0, 1);  
      $ed[2]=$edge['target']   = pg_fetch_result($query, 0, 2);  
      $ed[3]=$edge['the_geom'] = pg_fetch_result($query, 0, 3);  
echo"$ed[0] $ed[1] $ed[2] $ed[3] ";
      // Close database connection
      pg_close($con);

      return $ed[0];
   }


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

      case 'SPD' : // Shortest Path Dijkstra 
echo "edepa ";
        $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;";
        break;

      case 'SPA' : // Shortest Path A* 

        $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 astar_sp_delta(
                                '".TABLE."',
                                ".$startEdge['source'].",
                                ".$endEdge['target'].",
                                0.1)
                         ) as rt 
                    WHERE ".TABLE.".gid=rt.gid;";  
        break;

      case 'SPS' : // Shortest Path Shooting*

        $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 shootingstar_sp(
                                '".TABLE."',
                                ".$startEdge['gid'].",
                                ".$endEdge['gid'].",
                                0.1, 'length', true, true)
                         ) as rt 
                    WHERE ".TABLE.".gid=rt.gid;";
        break;   

   } // close switch

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

   // Perform database query
   $query = pg_query($dbcon,$sql); 


   // Return route as GeoJSON
   $geojson = array(
      'type'      => 'FeatureCollection',
      'features'  => array()
   ); 

   // Add edges to GeoJSON array
   while($edge=pg_fetch_assoc($query)) {  

      $feature = array(
         'type' => 'Feature',
         'geometry' => json_decode($edge['geojson'], true),
         'crs' => array(
            'type' => 'EPSG',
            'properties' => array('code' => '4326')
         ),
         'properties' => array(
            'id' => $edge['gid'],
            'length' => $edge['length']
         )
      );

      // Add feature array to feature collection array
      array_push($geojson['features'], $feature);
   }


   // Close database connection
   pg_close($dbcon);

   // Return routing result
   header('Content-type: application/json',true);
   echo json_encode($geojson);
2
  • Sorry, but part of this code is blowing my mind. Why do you declare undifined and compare things to it?
    – tmcw
    Feb 2, 2012 at 17:22
  • this code has been taken from a tutorial which i can't remember the link i'll try to find it!! though it doesn't seems to do something special i left it there just in case !!
    – john
    Feb 3, 2012 at 15:57

1 Answer 1

2

Your attached code looks like a pain :) Please use http://jsfiddle.net/

From what I seen you are using OpenLayers.Layer.Vector to get routes. Calls to the server are made through JavaScript XMLHttpRequest object and are limited by cross domain requests security policy. To solve that you need to use a proxy and set it with something like:

OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";

check: http://trac.osgeo.org/openlayers/wiki/FrequentlyAskedQuestions#ProxyHost

3
  • Thanks neil for your reply !! Sorry about the messy code :) i did what you said but nothing happened!! i put into my code as global OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url="; and inside my apache server at this path /opt/lampp/cgi-bin i put the proxy.cgi from this site and i also add to allowedHosts the 'localhost' but i couldn't get my data to be drawn at my map. Did i done something wrong to the prosses?
    – john
    Feb 3, 2012 at 15:13
  • Use firebug or chrome, the last offers better network information, to see if the json_url request is really doing and what is the result. This way you could see if this step is doing well.
    – acanimal
    Feb 3, 2012 at 17:49
  • Thanks neil it seams it was working after i put the OpenLayers.ProxyHost !!! But for some reason it doesn't draw the path i select but another path elsewere at the map (the same all the time)..Anyway thanks for your help Let me ask you something else though i want to built an app that uses tsp. could you give me some advaise how to start(i know there is a tsp function at pgrouting but i want to build my own)!
    – john
    Feb 5, 2012 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.