Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Openlayers/pgRouting

  • 18-04-2010 8:50pm
    #1
    Registered Users, Registered Users 2 Posts: 86 ✭✭


    I am trying to implement a routing application using openlayers and pgrouting. I am almost finished, however I cannot execute the final step. Basically I am using a php file to connect to the database, do the routing algorithm and give me back the points neededfor the routing in an xml file. That works fine. I then have a second file containing the map, and some javascript. Howeverthe function I am trying to use to read the xml just does not work. I have no idea why. Here is my code:

    <html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
    <style type="text/css">
    #map {
    width: 800px;
    height: 450px;
    border: 1px solid black;
    }

    </style>
    <!--<script type="text/javascript" src="test.php"></script>-->
    <script src="http://www.openlayers.org/api/OpenLayers.js"></script&gt;
    <script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script&gt;
    <script src="MapTest2.php?startpoint="+inverseMercator(startPoint.geometry.x,startPoint.geometry.y)+"&finalpoint="+inverseMercator(stopPoint.geometry.x,stopPoint.geometry.y)+"&srid=4326&plon="+lon+"&plat="+lat type="text/xml"></script>
    <script type="text/javascript">
    <!--
    // complex map object
    var map;
    var doc=null;

    //if (typeof document.all.EDGEXML != "undefined")
    //doc=EDGEXML;//.XMLDocument;
    //alert(doc);
    //doc=EDGEXML;

    // Start position for the map (hardcoded here for simplicity,
    // but maybe you want to get from URL params)
    var zoom=15;

    //var lat=<?php if($_REQUEST==53.34733||$_REQUEST==null||$_REQUEST==''||$_REQUEST=='undefined') echo 0; else echo $_REQUEST;?>;
    //var lon=<?php if($_REQUEST==-6.25907||$_REQUEST==null||$_REQUEST==''||$_REQUEST=='undefined') echo 0; else echo $_REQUEST;?>;

    var lat=null;
    var lon=null;

    <?php if($_REQUEST!=null){ echo "lat=".$_REQUEST.";";}?>
    <?php if($_REQUEST!=null){ echo "lon=".$_REQUEST.";";}?>

    if(lat==null)
    {
    lat=53.34733; //latitude
    lon =-6.25907;
    }
    //var lon =-6.451; //longitude

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

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

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

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

    function init(){
    map = new OpenLayers.Map('map',
    { maxExtent: new OpenLayers.Bounds(-6.451,53.179,-6.036,53.402),
    numZoomLevels: 19,
    maxResolution: 156543.0399,
    units: 'm',
    projection: new OpenLayers.Projection("EPSG:900913"),
    displayProjection: new OpenLayers.Projection("EPSG:4326")
    });

    var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");

    var layerTah = new OpenLayers.Layer.OSM.Osmarender("Tiles@Home");

    map.addLayers([layerMapnik,layerTah]);



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

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

    result = new OpenLayers.Layer.Vector("Routing results",
    {style: result_style});

    map.addLayer(start);
    map.addLayer(stop);
    map.addLayer(result);


    var lonLat = new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.projection);
    if (!map.getCenter()) map.setCenter (lonLat, zoom);

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

    OpenLayers.loadURL("./MapTest2.php?startpoint="+inverseMercator(startPoint.geometry.x,startPoint.geometry.y)+"&finalpoint="+inverseMercator(stopPoint.geometry.x,stopPoint.geometry.y)+"&srid=4326&plon="+lon+"&plat="+lat,
    //OpenLayers.loadURL("./MapTest2.php",
    OpenLayers.Util.getParameterString(result),
    null,
    displayRoute);
    }

    function toggleControl(element) {

    for (key in controls) {
    if (element.value == key && element.checked) {


    controls[key].activate();
    } else {
    controls[key].deactivate();
    }
    }
    }

    function inverseMercator(x, y) {

    var lon = (x / 20037508.34) * 180;
    var lat = (y / 20037508.34) * 180;

    lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

    return lon + " " + lat;
    }

    function inverseMercatorLon(lon){
    lon = (lon / 20037508.34) * 180;


    return lon;
    }

    function inverseMercatorLat(lat) {

    var lat = (lat / 20037508.34) * 180;

    lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

    return lat;
    }

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


    if (startPoint!=null && stopPoint!=null) {

    lon=inverseMercatorLon(map.getCenter().lon);
    lat=inverseMercatorLat(map.getCenter().lat);

    window.location.href="http://localhost:1980/routing2/ol_osm_routing/maptest1.php?startpoint="+inverseMercator(startPoint.geometry.x, startPoint.geometry.y)+"&finalpoint="+inverseMercator(stopPoint.geometry.x,stopPoint.geometry.y)+"&srid=4326&plon="+lon+"&plat="+lat;

    // OpenLayers.loadURL("routing.php?startpoint="+inverseMercator(startPoint.geometry.x, startPoint.geometry.y)+"&finalpoint="+inverseMercator(stopPoint.geometry.x,stopPoint.geometry.y)+"&method=SPD&srid=4326",
    //OpenLayers.loadURL("./routing.php",
    // OpenLayers.Util.getParameterString(result),
    // null,
    // displayRoute);
    }
    }



    function displayRoute(response) {
    if (response && response.responseXML) {
    // erase the previous results
    alert("I'm In");
    result.removeFeatures(result.features);

    // parse the features
    var edges = response.responseXML.getElementsByTagName('edge');
    //var edges = document.all.("SCRIPT").XMLDocument.getElementsByTagName('edge');
    //alert(response.responseXML.documentElement.text);
    var features = [];

    for (var i = 0; i < edges.length; i++) {

    var g = parser.read(edges.getElementsByTagName('wkt')[0].textContent);
    features.push(new OpenLayers.Feature.Vector(g));

    alert("in here");
    }
    result.addFeatures(features);
    }
    }


    function parseWKT(wkt) {


    parser = new OpenLayers.Format.WKT();

    var geometry = parser.read(wkt)


    var features = parser.read(wkt);
    var bounds;
    if(features) {

    if(features.constructor != Array) {
    features = [features];
    }
    for(var i=0; i<features.length; ++i) {
    if (!bounds) {
    bounds = features.geometry.getBounds();
    } else {
    bounds.extend(features.geometry.getBounds());
    }

    }
    result.addFeatures(features);

    } else {
    alert ("wrong");
    element.value = 'Bad WKT';
    }
    }

    // -->
    </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>

    <button onclick="compute()">Calculate Route</button>

    </body>
    </html>


    <?php
    ini_set('short_open_tag','Off');

    // Database connection settings
    define("PG_DB" , "routing");
    define("PG_HOST", "localhost");
    define("PG_PASS", "postgres");
    define("PG_USER", "postgres");
    define("PG_PORT", "5432");
    define("TABLE", "ways");


    // FUNCTION findNearestEdge
    function findNearestEdge($lonlat) {

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

    $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]-200)."
    ".($lonlat[1]-200).",
    ".($lonlat[0]+200)."
    ".($lonlat[1]+200).")'::box3d, 4326)
    ORDER BY dist LIMIT 1;";


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

    $edge = pg_fetch_result($query, 0, 0);
    $edge = pg_fetch_result($query, 0, 1);
    $edge = pg_fetch_result($query, 0, 2);
    $edge = pg_fetch_result($query, 0, 3);

    // Close database connection
    pg_close($dbcon);

    return $edge;
    }

    //http://localhost:1980/routing2/ol_osm_routing/routing.php?startpoint=-720023.40608569%207055317.3361107&finalpoint=%22-722698.7020752%207058909.8764395%22

    $counter = $pathlength = 0;

    //?startpoint=-6.452029968261393 53.399780357200676&finalpoint=-6.443768764495955 53.395263954164655&method=SPD&srid=4326

    if($_REQUEST!=null){

    // Retrieve start point
    $start = split(' ',$_REQUEST);

    $startPoint = array($start[0], $start[1]);



    // Retrieve end point
    $end = split(' ',$_REQUEST);

    $endPoint = array($end[0], $end[1]);



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


    $endEdge = findNearestEdge($endPoint);

    // Select the routing algorithm

    $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.",
    ".$endEdge.",
    3000)
    ) as rt
    WHERE ".TABLE.".gid=rt.gid;";

    // http://localhost:1980/routing2/ol_osm_routing/routing.php?startpoint=-6.45419%2053.40087&finalpoint=-6.44833%2053.40066

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

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


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

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


Comments

  • Closed Accounts Posts: 1 jozefvodny


    hallo, i like to ask you if you solved your problem. I have the same one and have no idea how to solve it.


Advertisement