dijkstra (#16) - nothing happen when the calculate route button is pressed (#383) - Message List

nothing happen when the calculate route button is pressed

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.

HTML file :

<html xmlns=" http://www.w3.org/1999/xhtml">

<head>

<style type="text/css">

#map {

width: 800px; height: 512px; border: 1px solid black;

}

</style> <script src="./OpenLayers-google/lib/OpenLayers.js"></script> <script src=" http://maps.google.com/maps?file=api&v=2&key=foobar"></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.styledefault?);

var stop_style = OpenLayers?.Util.applyDefaults({

externalGraphic: "stop.png", graphicWidth: 18, graphicHeight: 26, graphicYOffset: -26, graphicOpacity: 1

}, OpenLayers?.Feature.Vector.styledefault?);

var result_style = OpenLayers?.Util.applyDefaults({

strokeWidth: 3, strokeColor: "#ff0000", fillOpacity: 0

}, OpenLayers?.Feature.Vector.styledefault?);

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

function init() {

map = new OpenLayers?.Map('map', {projection: "EPSG: 54004",

units: "m", maxResolution: 156543.0339, maxExtent: new OpenLayers?.Bounds(-20037508,

-136554022, 20037508, 136554022)

});

map.addControl(new OpenLayers?.Control.LayerSwitcher?()); map.addControl(new OpenLayers?.Control.MousePosition?());

// create and add layers to the map var satellite = new OpenLayers?.Layer.GoogleMercator?("Google Satellite",

{type: G_NORMAL_MAP});

start = new OpenLayers?.Layer.Vector("Start point", {style: start_style}); stop = new OpenLayers?.Layer.Vector("End point", {style: stop_style}); 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((-13737893 6151394, -13737893 6141906, -13728396 6141906, -13728396 6151394, -13737893 6151394))"; var geometry = parser.read(wkt); var feature = new OpenLayers?.Feature.Vector(geometry); downtown.addFeatures([feature]);

// set default position map.zoomToExtent(new OpenLayers?.Bounds(-13737893,

6141906, -13728396, 6151394));

// 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]);

}

}

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: "victoria", srid: "54004"

}; OpenLayers?.loadURL("04.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>

PHP file :

<?php

// Database connection settings define("PG_DB" , "testdb"); define("PG_HOST", "localhost"); define("PG_USER", "postgres"); define("PG_PORT", "5432"); define("TABLE", "victoria");

$counter = $pathlength = 0;

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

// Retrieve end point $end = split(' ',$_REQUESTfinalpoint?); $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);

$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);

$edgegid? = pg_fetch_result($query, 0, 0); $edgesource? = pg_fetch_result($query, 0, 1); $edgetarget? = pg_fetch_result($query, 0, 2); $edgethe_geom? = pg_fetch_result($query, 0, 3);

// Close database connection pg_close($con);

return $edge;

}

// Select the routing algorithm switch($_REQUESTmethod?) {

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."', ".$startEdgesource?.", ".$endEdgetarget?.", 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."', ".$startEdgesource?.", ".$endEdgetarget?.", 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."', ".$startEdgegid?.", ".$endEdgegid?.", 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 += $edgelength?;

$xml .= "\t<edge id='".++$counter."'>\n"; $xml .= "\t\t<id>".$edgeid?."</id>\n"; $xml .= "\t\t<wkt>".$edgewkt?."</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;

?>

thanks before, ridhwan

  • Message #1622

    Hi Ridhwan,

    As far as I can see you use an old tutorial, which may not work anymore with newer versions of OpenLayers?. I have heard about some issues.

    So I recommend you to look at the 2010 workshop, which is just available for two weeks now: http://pgrouting.postlbs.org/wiki/WorkshopFOSS4G2010

    I think it has a more advanced PHP script and with GeoExt? + OpenLayers? your application looks much better.

    • Message #1625

      Dear Daniel, thank you for your answer. It really helped me.

      but, does it matter if the tutorial that I use is old version?

      actually, I just want to know how to connect between the PostgreSQL database that

      I created and Openlayers. Is there another way to my problems without having to

      change the tutorial that I use now?

      thanks before daniel

      • Message #1626

        Well, I think the latest tutorial is just more up-to-date and some parts have changed through user feedback of previous workshops. So in General it's of better quality and contains less errors. Furthermore:

        • The 2007 workshop used a non-official SVN sandbox version of OpenLayers?, 2010 workshop used the latest versions of GeoExt?
        • Instead of some "self-made" XML output of the PHP script it's a lot easier to make use of GeoJSON format that now PostGIS supports (this wasn't the case in 2007)

        That's why I recommend you to take a look at the latest workshop, but once you understood how it works, it won't matter if you use GeoExt? or not.

        • Message #1629

          I've downloaded the tutorial workshop2010 and when I read it, this tutorial requires linux (Ubuntu OS). This tutorial only practice how to install it on linux? how about windows?

          • Message #1630

            Can you explain to me how to use this tutorial? I really novice on the topic of GIS. I would be very happy if I could talk to you and ask about GIS. because I was confused to find a place to ask about this topic. My supervisor was not much help. I really want to understand this topic.

          • Message #1631

            Yes, the tutorial runs on Linux, but you can use a LiveDVD. It's all installed on the latest OSGeo LiveDVD. That means, you download the ISO image and create a DVD, or you use some software like VirtualBox? and you can load the ISO image as a virtual drive.

            Then, you can run Linux without having to install anything. It's all ready to start.

            Here the documentation how to get started with the LiveDVD:

            It's really convenient, because you won't mess up your system ;-)

            On the LiveDVD you will then find the same documents like these, which provide an overview and quickstart document for pgRouting. At the end of the quickstart document there is a note, where to find the pgRouting workshop:

            Hope that helps.