Modified: sis/sandbox/gsoc2013/crimgeoprofile/js/index.js URL: http://svn.apache.org/viewvc/sis/sandbox/gsoc2013/crimgeoprofile/js/index.js?rev=1525754&r1=1525753&r2=1525754&view=diff ============================================================================== --- sis/sandbox/gsoc2013/crimgeoprofile/js/index.js (original) +++ sis/sandbox/gsoc2013/crimgeoprofile/js/index.js Tue Sep 24 00:12:22 2013 @@ -1,319 +1,137 @@ -var data_obj; -var map; -var findroutes, first, first_transit; -var start_tp, end_tp; -var first_sim = 0; -$(document).ready(function () { - - map = L.map('map').setView([51.505, 21], 1); - L.tileLayer('http://{s}.tile.cloudmade.com/e7b61e61295a44a5b319ca0bd3150890/997/256/{z}/{x}/{y}.png', { - attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>', - maxZoom: 18 - }).addTo(map); - init(); +var data_obj; //object +var map; //map +var findroutes, first, first_transit; //variables used to alert user if the appropriate steps have not been completed +var first_sim = 0; //whether first week has been simulated for routine activity +var ddcount = 0; //number of ajax calls made for simulating distance decay +var equity = 0; //initial equity of the agent for simulting distance decay +var dist = 0; //distacne travelled by the agent while simulating distance decay in the last iteration +var distnow = 0; //maximum distance the agent can travel in the path currently calculated +var crime_spot_markers = new Array(); //stores the markers for the crime spots +var stopdd = 0; //whether simualion of distance decay should be stopped +var gpcount = 0; //number of reties made for ajax call to "routing2.php" +var gpcount2 = 0; //number of retreis made for ajax call to "ajax.php" + +$(document).ready(function () { //when dom elements have been loaded + init(); //initalize object + //style toolbar $('#toolbar1').buttonset(); $('#toolbar2').buttonset(); $('#toolbar3').buttonset(); $('#showmap').button(); - //map = L.map('map').setView([51.505, 21], 1); + //set map + map = L.map('map').setView([data_obj.city_lat, data_obj.city_lon], data_obj.zoom); L.tileLayer('http://{s}.tile.cloudmade.com/e7b61e61295a44a5b319ca0bd3150890/997/256/{z}/{x}/{y}.png', { attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>', maxZoom: 18 }).addTo(map); - $('#addhome').click(function(){ + //Associating functions with click of corresponding buttons + $('#addhome').click(function(){ //"Mark Home" button map.on('click', markHome); }); - $('#addoffice').click(function(){ + $('#addoffice').click(function(){ //"Mark Office" button map.on('click', markOffice); }); - $('#addbar').click(function(){ + $('#addbar').click(function(){ //"Mark Bar" button map.on('click', markBar); }); - $('#addluncha').click(function(){ + $('#addluncha').click(function(){ //"Mark Lunch-A" button map.on('click', markLunchA); }); - $('#addlunchb').click(function(){ + $('#addlunchb').click(function(){ //"Mark Lunch-B" button map.on('click', markLunchB); }); - $('#addmall').click(function(){ + $('#addmall').click(function(){ //"Mark Mall" button map.on('click', markMall); }); - $("#addcrime").click(function(){ + $("#addcrime").click(function(){ //"Mark Crime Spot" button map.on('click', markCrimeSpot); }) - $('#findroutes').click(function(){ - if(data_obj.loc_num!=6){ + $('#findroutes').click(function(){ //"Initalilize Schedule" button + if(data_obj.num_locations!=6){ //If all locations ahve not been marked, alert the user alert("You must mark all locations: Home, office, bar, Lunch-A, Lunch-B, Mall!!! Try again after marking them"); } else{ - data_obj.sch_init = 1; + data_obj.sch_init = 1; //Schedule ahs been initalized $("#loading").dialog('open').html("<p>Finding Beeline Route Times between all pair of locations marked and initializing schedule. Please Wait... You can proceed to simulate Routine Activity once this dialog closes</p>"); - showRoutes(); + showRoutes(); //find routes } }); -/* $('#transit').click(function(){ - map.off('click', markTransit); - if(tdata!=""){ - tdata=tdata.substring(0,tdata.length-1); - tdata="["+tdata+"],"; - transit_arr[starttp][endtp]=tdata; - } - tdata=""; - startp=0; - endtp=0; - $("#dialog" ).dialog( "open" ); - });*/ - $('#simulate').click(function(){ - if(findroutes==0){ - alert("You need to click on 'Find Routes' first"); - } - else{ - if(first==0){ - var options1= ""; - for(var i=0; i < data_obj.num_locations; i++){ - options1+="<option value='"+i+"'>"+(i+1)+"</option>\n"; - } - - $("#start").append(options1); - $("#end").append(options1); - var options2= ""; - for(var i=1; i<10000; i++){ - options2+="<option value='"+i+"'>"+i+"</option>\n"; - } - options2+="<option selected='selected' value='10000'>10000</option>\n"; - //$("#times").append(options2); - first=1; - } - $("#dialog2" ).dialog( "open" ); - - } - - }); - $('#showmap').click(function(){ + + $('#showmap').click(function(){ //"Show" button var city=$('#city').val(); + //find lat long of city and focus map to that city addScript('http://open.mapquestapi.com/nominatim/v1/search.php?format=json&json_callback=getLatLon&q='+city); }); - $('#showroutes').click(function(){ - $("#loading").dialog('open').html("<p>Finding Beeline Route Time between all poosible pair of locations and initializing schedule. Please Wait... You can proceed to simulate Routine Activity once this dialog closes</p>"); - showRoutes(); - }); - $('#showdata').click(function(){ - console.log(JSON.stringify(data_obj, null, 4)); - }); - - $('#save').click(function(){ - - var filename = prompt("Save As: "); + $('#save').click(function(){ //"Save" button + var filename = prompt("Save As: "); //prompt user for name to save as + //make ajax request ti server side script "save.php" to save data $.ajax({ type: "POST", url: "save.php", dataType : 'json', - data : { - - json : JSON.stringify(data_obj, null, 4) , - fname : filename + data : { + geojson : generateGeoJson(data_obj) , //save spatial data as GeoJSON format + json : generateJson(), //save non-spatial data as JSON format + fname : filename, //name to save as }, - success: function(){ - alert("Saved"); + success: function(data){ + alert(data); } }); }); - $('#load').click(function(){ - var filename = prompt("Filename: "); + $('#load').click(function(){ //"Load" button + var filename = prompt("Filename: "); //prompt user for file-name to load $("#loading").dialog('open').html("<p>Loading ... Please wait</p>"); - $.ajax({ - url: filename, - dataType: 'json', - success: function (data){ - data_obj = data; - display(); - $("#loading").dialog('close'); - } + init(); //initalize object + clearMap(); //clear map + //make ajax call to get data from the server + $.ajax({ //loading non-spatial data which has been saved as JSON frormat + url: filename, + dataType: 'json', + success: function (data){ + data_obj = data; + $.ajax({ //loading spatial data which has been saved as GeoJSON frormat + url: filename+'_geo', + dataType: 'json', + success: function (data2){ + load(data2); + $("#loading").dialog('close'); + } + }); + } }); - }); - $('#clear').click(function(){ + $('#clear').click(function(){ //Reset Button window.location.href = window.location.pathname; }); - $('#marktransit').click(function(){ - if(first_transit==0){ - var options1= ""; - for(var i=0; i < data_obj.num_locations; i++){ - options1+="<option value='"+i+"'>"+(i+1)+"</option>\n"; - } - $("#transit_start").append(options1); - $("#transit_end").append(options1); - first_transit=1; - } - $("#dialog" ).dialog( "open" ); - }); - - $('#random').click(function(){ - var options1= ""; - for(var i=0; i < data_obj.num_locations; i++){ - options1+="<option value='"+i+"'>"+(i+1)+"</option>\n"; - } - $("#random_start").append(options1); - $("#random_end").append(options1); - $("#dialog3" ).dialog( "open" ); - }); - - $('#hybrid').click(function(){ - var options1= ""; - for(var i=0; i < data_obj.num_locations; i++){ - options1+="<option value='"+i+"'>"+(i+1)+"</option>\n"; - } - $("#hybrid_start").append(options1); - $("#hybrid_end").append(options1); - $("#dialog4" ).dialog( "open" ); - }); - - $('#routine').click(function(){ + $('#routine').click(function(){ //"Simualate Routine Activity" Button if(data_obj.sch_init == 0){ alert("You must initialize schedule first. Try again after clicking on 'Initialize Schedule'"); } else{ - sortTime(); - initSchedule(); - simulateRoutineActivity(); + sortTime(); //sorting beeline routes accoring the time take to traverse those routes + initSchedule(); //initalizing schedule + simulateRoutineActivity(); //simulating routine activty } }); - //dialogs - - $( "#dialog" ).dialog({ - resizable: true, - height:300, - width :500, - modal: true, - buttons: { - Ok: function() { - $( this ).dialog( "close" ); - starttp = parseInt($("#transit_start").val(),10)+1; - endtp = parseInt($("#transit_end").val(),10)+1; - map.on('click', markTransit); - } - }, - autoOpen: false, + $('#dd').click(function(){ //"Simualate Distance Decay" Button + $("#info").dialog('open').html("<p>Simulating.....</p>"); + equity = 100; //inital equity + dist = 0; + distnow = 0; + ddcount = 1; + stopdd = 0; + simulateDistanceDecay(); //simulate distacne decay }); - $( "#dialog2" ).dialog({ - resizable: true, - height:300, - width :500, - modal: true, - buttons: { - Ok: function() { - $( this ).dialog( "close" ); - var start = $("#start").val(); - var end = $("#end").val(); - var times = $("#times").val(); - simulateBeeline($("#start").val(), $("#end").val()); - } - }, - autoOpen: false, - }); - - $( "#dialog3" ).dialog({ - resizable: true, - height:300, - width :500, - modal: true, - buttons: { - Ok: function() { - $( this ).dialog( "close" ); - var start_rand = Number($("#random_start").val()); - var end_rand = Number($("#random_end").val()); - - - var start_lat = data_obj.locations[start_rand].lat; - var start_lon = data_obj.locations[start_rand].lng; - var end_lat = data_obj.locations[end_rand].lat; - var end_lon = data_obj.locations[end_rand].lng; - var time = $("#time").val(); - //console.log("("+start_lat+","+start_lon+","+end_lat+","+end_lon+","+time+")"); - var randomsim = $.ajax({ - type: "POST", - url: "routing.php", - data : { - start_lat : start_lat , - start_lon : start_lon , - end_lat : end_lat , - end_lon : end_lon , - time : time - }, - success: function(data){ - var rand_path = data; - //alert(rand_path); - var pt, pts = []; - for (var i=0; i<rand_path.route_geometry.length; i++){ - pt = new L.LatLng(rand_path.route_geometry[i][0] , rand_path.route_geometry[i][1]); - pts.push(pt); - } - route= new L.Polyline(pts, { - weight: 3, - opacity: 0.5, - color: 'blue', - smoothFactor: 1 - }).addTo(map); - route.bringToFront(); - } - }); - } - }, - autoOpen: false, - }); + //Styling dialogs - $( "#dialog4" ).dialog({ - resizable: true, - height:300, - width :500, - modal: true, - buttons: { - Ok: function() { - $( this ).dialog( "close" ); - var start_rand = Number($("#hybrid_start").val()); - var end_rand = Number($("#hybrid_end").val()); - var start_lat = data_obj.locations[start_rand].lat; - var start_lon = data_obj.locations[start_rand].lng; - var end_lat = data_obj.locations[end_rand].lat; - var end_lon = data_obj.locations[end_rand].lng; - var time = $("#hybrid_time").val(); - //console.log("Hybrid("+start_lat+","+start_lon+","+end_lat+","+end_lon+","+time+")"); - $.ajax({ - type: "POST", - url: "hybrid.php", - data : { - start_lat : start_lat , - start_lon : start_lon , - end_lat : end_lat , - end_lon : end_lon , - time : time - }, - success: function(data){ - var obj = data; - var pt, pts = []; - for (var i=0; i<obj.length; i++){ - pt = new L.LatLng(obj[i][0] , obj[i][1]); - pts.push(pt); - } - route= new L.Polyline(pts, { - weight: 3, - opacity: 0.5, - color: 'green', - smoothFactor: 1 - }).addTo(map); - route.bringToFront(); - } - }); - } - }, - autoOpen: false, - }); + //Dialog to display when routine activity is being simualated $("#loading").dialog({ modal: true, hide: 'slide', @@ -322,4 +140,10 @@ $(document).ready(function () { closeOnEscape: false, open: function(event, ui) { $(".ui-dialog-titlebar-close", ui.dialog || ui).hide(); } }); + //Dialog to display when Distance Decay is being simulated + $("#info").dialog({ + modal: true, + autoOpen: false, + buttons: { "Stop Simulation": function() { updateSpotLabels(); stopdd = 1; $(this).dialog("close"); } } + }); }); \ No newline at end of file
Modified: sis/sandbox/gsoc2013/crimgeoprofile/js/leaflet_numbered_markers.js URL: http://svn.apache.org/viewvc/sis/sandbox/gsoc2013/crimgeoprofile/js/leaflet_numbered_markers.js?rev=1525754&r1=1525753&r2=1525754&view=diff ============================================================================== --- sis/sandbox/gsoc2013/crimgeoprofile/js/leaflet_numbered_markers.js (original) +++ sis/sandbox/gsoc2013/crimgeoprofile/js/leaflet_numbered_markers.js Tue Sep 24 00:12:22 2013 @@ -1,33 +1,33 @@ -L.NumberedDivIcon = L.Icon.extend({ - options: { - // EDIT THIS TO POINT TO THE FILE AT http://www.charliecroom.com/marker_hole.png (or your own marker) - iconUrl: '<%= image_path("marker_hole.png") %>', - number: '', - shadowUrl: null, - iconSize: new L.Point(25, 41), - iconAnchor: new L.Point(13, 41), - popupAnchor: new L.Point(0, -33), - /* - iconAnchor: (Point) - popupAnchor: (Point) - */ - className: 'leaflet-div-icon' - }, - - createIcon: function () { - var div = document.createElement('div'); - var img = this._createImg(this.options['iconUrl']); - var numdiv = document.createElement('div'); - numdiv.setAttribute ( "class", "number" ); - numdiv.innerHTML = this.options['number'] || ''; - div.appendChild ( img ); - div.appendChild ( numdiv ); - this._setIconStyles(div, 'icon'); - return div; - }, - - //you could change this to add a shadow like in the normal marker if you really wanted - createShadow: function () { - return null; - } +L.NumberedDivIcon = L.Icon.extend({ + options: { + // EDIT THIS TO POINT TO THE FILE AT http://www.charliecroom.com/marker_hole.png (or your own marker) + iconUrl: '<%= image_path("marker_hole.png") %>', + number: '', + shadowUrl: null, + iconSize: new L.Point(25, 41), + iconAnchor: new L.Point(13, 41), + popupAnchor: new L.Point(0, -33), + /* + iconAnchor: (Point) + popupAnchor: (Point) + */ + className: 'leaflet-div-icon' + }, + + createIcon: function () { + var div = document.createElement('div'); + var img = this._createImg(this.options['iconUrl']); + var numdiv = document.createElement('div'); + numdiv.setAttribute ( "class", "number" ); + numdiv.innerHTML = this.options['number'] || ''; + div.appendChild ( img ); + div.appendChild ( numdiv ); + this._setIconStyles(div, 'icon'); + return div; + }, + + //you could change this to add a shadow like in the normal marker if you really wanted + createShadow: function () { + return null; + } }); \ No newline at end of file Added: sis/sandbox/gsoc2013/crimgeoprofile/queries.sql URL: http://svn.apache.org/viewvc/sis/sandbox/gsoc2013/crimgeoprofile/queries.sql?rev=1525754&view=auto ============================================================================== --- sis/sandbox/gsoc2013/crimgeoprofile/queries.sql (added) +++ sis/sandbox/gsoc2013/crimgeoprofile/queries.sql Tue Sep 24 00:12:22 2013 @@ -0,0 +1,19 @@ +CREATE OR REPLACE VIEW road_ext_indiana AS + SELECT *, st_startpoint(geom), st_endpoint(geom) + FROM roads; + + CREATE TABLE node_indiana AS + SELECT row_number() OVER (ORDER BY foo.p)::integer AS id, + foo.p AS the_geom + FROM ( + SELECT DISTINCT road_ext_indiana.st_startpoint AS p FROM road_ext_indiana + UNION + SELECT DISTINCT road_ext_indiana.st_endpoint AS p FROM road_ext_indiana + ) foo + GROUP BY foo.p; + + CREATE TABLE network_indiana AS + SELECT a.*, b.id as start_id, c.id as end_id, st_length(a.geom) as st_length + FROM road_ext_indiana AS a + JOIN node_indiana AS b ON a.st_startpoint = b.the_geom + JOIN node_indiana AS c ON a.st_endpoint = c.the_geom; \ No newline at end of file Modified: sis/sandbox/gsoc2013/crimgeoprofile/routing.php URL: http://svn.apache.org/viewvc/sis/sandbox/gsoc2013/crimgeoprofile/routing.php?rev=1525754&r1=1525753&r2=1525754&view=diff ============================================================================== --- sis/sandbox/gsoc2013/crimgeoprofile/routing.php (original) +++ sis/sandbox/gsoc2013/crimgeoprofile/routing.php Tue Sep 24 00:12:22 2013 @@ -1,19 +1,19 @@ <?php - +/*The following function is used for simualting random movement on agent on the map for simulating Routine Activity. Input parameters are Latitude of Start point, Longitude of start point, Latitude of destination point, Longitude of destination point, and the time available respectively. */ function random_movement($start_lat, $start_long, $dest_lat, $dest_long, $given_time){ - + //connecting to database which has open street map data converted into a routable network $con = pg_connect("host=localhost port=5432 dbname=template_postgis_20 user=postgres password=a"); //finding nearest node to destination - $query = "SELECT * FROM node_taiwan - ORDER BY geom <-> ST_GeometryFromText('POINT(".$dest_long." ".$dest_lat.")',4326) - LIMIT 1;"; - + $query = "SELECT * FROM node_indiana + ORDER BY the_geom <-> ST_GeometryFromText('POINT(".$dest_long." ".$dest_lat.")',4326) + LIMIT 1;"; $result = pg_query($con, $query); $row = pg_fetch_row($result); $dest_id = $row[0]; - $query = "SELECT geom FROM node_taiwan WHERE id = ".$dest_id.";"; + //getting the geometry of the destination node + $query = "SELECT the_geom FROM node_indiana WHERE id = ".$dest_id.";"; $result = pg_query($con, $query); $row = pg_fetch_row($result); $geom = $row[0]; @@ -24,13 +24,13 @@ function random_movement($start_lat, $st $dest_y = $row[0]; //find nearest road to given point - $query = "SELECT * FROM network_taiwan + $query = "SELECT * FROM network_indiana ORDER BY geom <-> ST_GeometryFromText('POINT(".$start_long." ".$start_lat.")',4326) LIMIT 1;"; $result = pg_query($con, $query); $row = pg_fetch_row($result); - $start_id = $row[13]; - $end_id = $row[14]; + $start_id = $row[12]; + $end_id = $row[13]; $curr_road_id = $row[1]; $route = array(); $xc = array(); @@ -52,146 +52,102 @@ function random_movement($start_lat, $st $first = 1; $time = 0; $prev_node; - while(1){ - //echo $curr_node."<br>"; - //stroing route - $query = "SELECT geom FROM node_taiwan WHERE id = ".$curr_node.";"; + while(1){ + //getting geometry of current node + $query = "SELECT the_geom FROM node_indiana WHERE id = ".$curr_node.";"; $result = pg_query($con, $query); $row = pg_fetch_row($result); $geom = $row[0]; + + //getting x and y coordinates of current node $query = "SELECT ST_X('".$geom."'),ST_Y('".$geom."') ;"; $result = pg_query($con, $query); $row = pg_fetch_row($result); + + //stroing x and y coordinates $curr_x = $row[1]; $curr_y = $row[0]; $xc[$n] = $curr_x; $yc[$n] = $curr_y; + + //stroing nodes along the route $route[$n] = $curr_node; $n++; - //computing time traversed in last hop + //If the previous node was the starting point if($first == 1){ - /*$url = 'http://routes.cloudmade.com/81aa79a9504e4430a8a32f491ef96f07/api/0.3/'.$start_lat.','.$start_long.','.$curr_x.','.$curr_y.'/car.js'; - $aContext = array( - 'http' => array( - 'proxy' => 'tcp://10.3.100.212:8080', - 'request_fulluri' => true, - 'header' => 'Accept-Charset: UTF-8, *;q=0' - ), - ); - $cxContext = stream_context_create($aContext); - $sFile = file_get_contents($url, False, $cxContext); - $obj = json_decode($sFile); - $t2 = $obj->route_summary->total_time; - $time = $time + ((double)$t2)/60.0; - //echo $time.";TIME<br>";*/ - $query = "SELECT ST_Distance(ST_GeographyFromText('POINT(".$start_long." ".$start_lat.")'),ST_GeographyFromText('POINT(".$curr_y." ".$curr_x.")'))"; - // echo $query."<br>"; + //computing distance traversed in the last strectch of movement from one intersection to the next + $query = "SELECT ST_Distance(ST_GeographyFromText('POINT(".$start_long." ".$start_lat.")'),ST_GeographyFromText('POINT(".$curr_y." ".$curr_x.")'))"; $result = pg_query($con, $query); - $row = pg_fetch_row($result); - //echo $row[0]."<br>"; - $time = ((double)$row[0])/111/1*60; - + $row = pg_fetch_row($result); + $time = ((double)$row[0])/111/1*60; $first = 0; } + //If the previous node was not the starting point else{ - $query = "SELECT st_length FROM network_taiwan WHERE (start_id = ".$prev_node." AND end_id =".$curr_node." ) OR (start_id = ".$curr_node." AND end_id =".$prev_node." );"; - - - /* - $query = "SELECT * FROM pgr_dijkstra(' - SELECT gid AS id, - start_id::int4 AS source, - end_id::int4 AS target, - st_length::float8 AS cost - FROM network_taiwan', - ".$prev_node.", - ".$curr_node.", - false, - false);";*/ - //echo $query."<br>"; + //computing distance traversed in the last strectch of movement from one intersection to the next + $query = "SELECT st_length FROM network_indiana WHERE (start_id = ".$prev_node." AND end_id =".$curr_node." ) OR (start_id = ".$curr_node." AND end_id =".$prev_node." );"; $result = pg_query($con, $query); $cost = 0.0; $row = pg_fetch_row($result); - $cost=(double)$row[0]; - //echo $cost; - $t2 = (double)$cost*111/5*60; - - $time = $time + (double)$t2; - //echo $time.";TIME<br>"; + $cost=(double)$row[0]; + $t2 = (double)$cost*111/5*60; + $time = $time + (double)$t2; } - //finding time from current node to destination - /* $query = "SELECT geom FROM node_taiwan WHERE id = ".$curr_node.";"; - $result = pg_query($con, $query); - $row = pg_fetch_row($result); - $geom = $row[0]; - $query = "SELECT ST_X('".$geom."'),ST_Y('".$geom."') ;"; - $result = pg_query($con, $query); - $row = pg_fetch_row($result); - $curr_x = $row[1]; - $curr_y = $row[0]; */ - - $query = 'SELECT geom FROM node_taiwan WHERE id = '.$curr_node.';'; + //getting geometry of current node + $query = 'SELECT the_geom FROM node_indiana WHERE id = '.$curr_node.';'; $result = pg_query($con, $query); $row = pg_fetch_row($result); $geom1 = "'".$row[0]."'"; - $query = 'SELECT geom FROM node_taiwan WHERE id = '.$dest_id.';'; + //gettng geometry of destination node + $query = 'SELECT the_geom FROM node_indiana WHERE id = '.$dest_id.';'; $result = pg_query($con, $query); $row = pg_fetch_row($result); $geom2 = "'".$row[0]."'"; - $query = 'SELECT ST_distance('.$geom1.','.$geom2.');'; - // echo $query."<br>"; + //calculating distance between current node and destination + $query = 'SELECT ST_distance('.$geom1.','.$geom2.');'; $result = pg_query($con, $query); $row = pg_fetch_row($result); $dist = $row[0]; - $t2 = (double)$dist/111/1*60;; - - - //echo $time." ".$t2."<br>"; + $t2 = (double)$dist/111/1*60; + //if time runs out break from loop if($t2 > $given_time - $time - 15) break; - //if($n==3)break; + //else get all roads at this intersection - $query = 'SELECT geom from node_taiwan WHERE id = '.$curr_node.';'; + $query = 'SELECT the_geom from node_indiana WHERE id = '.$curr_node.';'; $result = pg_query($con, $query); $row = pg_fetch_row($result); - $geom = "'".$row[0]."'"; - - $query = 'SELECT start_id, end_id FROM network_taiwan WHERE st_dwithin(network_taiwan.geom, '.$geom.' , 0)'; - /*$query = "SELECT osm_id FROM network_taiwan - WHERE - network_taiwan.start_id = ".$curr_node." OR network_taiwan.end_id = ".$curr_node.";";*/ - //echo $query.";QUERY<br>"; + $geom = "'".$row[0]."'"; + $query = 'SELECT start_id, end_id FROM network_indiana WHERE st_dwithin(network_indiana.geom, '.$geom.' , 0)'; $result = pg_query($con, $query); - //echo $query."<br>"; - + //stroing all roads from this intersection except the road thruogh which the agent came $way = array(); $num = 0; while($row = pg_fetch_row($result)){ $tmp1 = $row[0]; $tmp2 = $row[1]; - if($tmp1 != $curr_node && $tmp1 != $prev_node){ - //echo $tmp." ttttttt<br>"; - $points[$num++] = $tmp1; - } - if($tmp2 != $curr_node && $tmp2 != $prev_node){ - //echo $tmp." ttttttt<br>"; - $points[$num++] = $tmp2; + if($tmp1 != $curr_node){ + $points[$num++] = $tmp1; } - } - //echo "NUM: ".$num."<br>"; - + if($tmp2 != $curr_node){ + $points[$num++] = $tmp2; + } + } + //updating variables $prev_node = $curr_node; + + //handling cases where the agent meets a dead end if($num == 0){ - if($n>1){ - //echo "INNUM0<br>"; - + //If the prevoius point was not the starting point, go back to the previous node and continue + if($n>1){ $curr_node = $route[$n-2]; } + //If the previous node was the starting point, move in the other direction of the raod (i.e. different formt eh one chosen previously else{ if((int)$curr_node === (int)$row_st[0]){ $curr_node = $row_st[1]; @@ -200,43 +156,16 @@ function random_movement($start_lat, $st $curr_node = $row_st[0]; } } - } + } + //If the agent does not meet a dead end else{ //choosing a new road randomly - $ran = rand(0,$num-1); - //print "ROADS<br>"; - //print_r($points); - $curr_node = $points[$ran]; - //echo $ran."<br>"; - /* $curr_road_id = $way[$ran]; - $query = "SELECT start_id, end_id FROM network_taiwan - WHERE - network_taiwan.osm_id = ".$curr_road_id.";"; - //echo $query."<br>"; - $result = pg_query($con, $query); - $row = pg_fetch_row($result); - $start_id = $row[0]; - $end_id = $row[1]; - //echo "CURR_NODE".$curr_node."<br>"; - //echo "START_ID".$start_id."<br>"; - //echo "END_ID".$end_id."<br>"; - if((int)$curr_node === (int)$start_id){ - $curr_node = $end_id; - //echo "IN1"; - } - else if((int)$curr_node === (int)$end_id){ - $curr_node = $start_id; - //echo "IN2"; - } */ - } - - //finding the other end of the new road - - //echo "NEW_CURR_NODE".$curr_node."<br>"; + $ran = rand(0,$num-1); + $curr_node = $points[$ran]; + } } - //moving to destination by the shortest path; - $url = 'http://routes.cloudmade.com/81aa79a9504e4430a8a32f491ef96f07/api/0.3/'.$start_lat.','.$start_long.','; - + //moving to destination by the shortest path after the time has run out + $url = 'http://routes.cloudmade.com/81aa79a9504e4430a8a32f491ef96f07/api/0.3/'.$start_lat.','.$start_long.','; if($n>0){ $url = $url.'['; for($i=0; $i<$n; $i++){ @@ -245,9 +174,7 @@ function random_movement($start_lat, $st } $url = $url.'],'; } - $url = $url.$dest_lat.','.$dest_long.'/car.js'; - - //echo $url."<br>"; + $url = $url.$dest_lat.','.$dest_long.'/foot.js'; $aContext = array( 'http' => array( @@ -257,36 +184,22 @@ function random_movement($start_lat, $st ), ); $cxContext = stream_context_create($aContext); - $sFile = file_get_contents($url); - + //calculating shortest path + $sFile = file_get_contents($url, False, $cxContext); + //header for json content to be sent to the client header('Content-Type: application/json'); - echo $sFile; - - - - //echo $query; - //$result = pg_query($con, $query); - //echo "DIJSKTRA<br>"; - //while($row = pg_fetch_row($result)){ - //$route[$n++] = $row[1]; - //echo $row[1]."<br>"; - //} - //echo "FINAL<br>"; - /*for($i=0;$i<$n;$i++){ - echo $route[$i]."<br>"; - } */ - - + //printing route to be sent to the client + echo $sFile; } -//getting POST data and calling function +/*variables received via ajax request from client i.e Latitude of Start point, Longitude of start point, Latitude of destination point, Longitude of destination point, and the time available respectively */ $start_lat = $_POST['start_lat']; $start_lon = $_POST['start_lon']; $dest_lat = $_POST['end_lat']; $dest_lon = $_POST['end_lon']; $time = $_POST['time']; -//random_movement(25.048202776784258,121.52071952819824,25.044314791294198,121.53668403625488,200); +//calling function for random motion with required parameters random_movement($start_lat, $start_lon, $dest_lat, $dest_lon, $time); ?> Added: sis/sandbox/gsoc2013/crimgeoprofile/routing2.php URL: http://svn.apache.org/viewvc/sis/sandbox/gsoc2013/crimgeoprofile/routing2.php?rev=1525754&view=auto ============================================================================== --- sis/sandbox/gsoc2013/crimgeoprofile/routing2.php (added) +++ sis/sandbox/gsoc2013/crimgeoprofile/routing2.php Tue Sep 24 00:12:22 2013 @@ -0,0 +1,211 @@ +<?php +/*The following function is used for simualting random movement on agent on the map for simulating distance decay. Input parameters are Latitude of Start point, Longitude of start point, Latitude of destination point, Longitude of destination point, and the time available respectively. The diffence from Routing Activity here is that the route is calcuted till the time runs out and the agent does nto move to the destination after that - that part of moving to the destination or coninuing random motion is decided on the client side based on which a crime ahs been committed or not*/ +function random_movement($start_lat, $start_long, $dest_lat, $dest_long, $given_time){ + //connecting to database which has open street map data converted into a routable network + $con = pg_connect("host=localhost port=5432 dbname=template_postgis_20 user=postgres password=a"); + + //finding nearest node to destination + $query = "SELECT * FROM node_indiana + ORDER BY the_geom <-> ST_GeometryFromText('POINT(".$dest_long." ".$dest_lat.")',4326) + LIMIT 1;"; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $dest_id = $row[0]; + + //getting the geometry of the destination node + $query = "SELECT the_geom FROM node_indiana WHERE id = ".$dest_id.";"; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $geom = $row[0]; + $query = "SELECT ST_X('".$geom."'),ST_Y('".$geom."') ;"; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $dest_x = $row[1]; + $dest_y = $row[0]; + + //find nearest road to given point + $query = "SELECT * FROM network_indiana + ORDER BY geom <-> ST_GeometryFromText('POINT(".$start_long." ".$start_lat.")',4326) + LIMIT 1;"; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $start_id = $row[12]; + $end_id = $row[13]; + $curr_road_id = $row[1]; + $route = array(); + $xc = array(); + $yc = array(); + $n=0; + + //decide randomly whether to move up or down the road + $ran = rand(0,1); + $curr_node = 0; + $row_st[0] = $start_id; + $row_st[1] = $end_id; + if($ran == 0){ + $curr_node = $row_st[0]; + } + else{ + $curr_node = $row_st[1]; + } + $flag = 1; + $first = 1; + $time = 0; + $prev_node; + while(1){ + //getting geometry of current node + $query = "SELECT the_geom FROM node_indiana WHERE id = ".$curr_node.";"; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $geom = $row[0]; + + //getting x and y coordinates of current node + $query = "SELECT ST_X('".$geom."'),ST_Y('".$geom."') ;"; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + + //stroing x and y coordinates + $curr_x = $row[1]; + $curr_y = $row[0]; + $xc[$n] = $curr_x; + $yc[$n] = $curr_y; + + //stroing nodes along the route + $route[$n] = $curr_node; + $n++; + + //If the previous node was the starting point + if($first == 1){ + //computing distance traversed in the last strectch of movement from one intersection to the next + $query = "SELECT ST_Distance(ST_GeographyFromText('POINT(".$start_long." ".$start_lat.")'),ST_GeographyFromText('POINT(".$curr_y." ".$curr_x.")'))"; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $time = ((double)$row[0])/111/1*60; + $first = 0; + } + //If the previous node was not the starting point + else{ + //computing distance traversed in the last strectch of movement from one intersection to the next + $query = "SELECT st_length FROM network_indiana WHERE (start_id = ".$prev_node." AND end_id =".$curr_node." ) OR (start_id = ".$curr_node." AND end_id =".$prev_node." );"; + $result = pg_query($con, $query); + $cost = 0.0; + $row = pg_fetch_row($result); + $cost=(double)$row[0]; + $t2 = (double)$cost*111/5*60; + //echo "DIST:".(double)($cost*111)."<br>"; + $time = $time + (double)$t2; + } + + //getting geometry of current node + $query = 'SELECT the_geom FROM node_indiana WHERE id = '.$curr_node.';'; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $geom1 = "'".$row[0]."'"; + + //gettng geometry of destination node + $query = 'SELECT the_geom FROM node_indiana WHERE id = '.$dest_id.';'; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $geom2 = "'".$row[0]."'"; + + //calculating distance between current node and destination + $query = 'SELECT ST_distance('.$geom1.','.$geom2.');'; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $dist = $row[0]; + $t2 = (double)$dist/111/1*60; + + //if time runs out break from loop + if($t2 > $given_time - $time - 15) break; + + //else get all roads at this intersection + $query = 'SELECT the_geom from node_indiana WHERE id = '.$curr_node.';'; + $result = pg_query($con, $query); + $row = pg_fetch_row($result); + $geom = "'".$row[0]."'"; + + $query = 'SELECT start_id, end_id FROM network_indiana WHERE st_dwithin(network_indiana.geom, '.$geom.' , 0)'; + $result = pg_query($con, $query); + + //stroing all roads from this intersection except the road thruogh which the agent came + $way = array(); + $num = 0; + $count = 0; + while($row = pg_fetch_row($result)){ + $count++; + $tmp1 = $row[0]; + $tmp2 = $row[1]; + if($tmp1 != $curr_node){ + $points[$num++] = $tmp1; + } + if($tmp2 != $curr_node){ + $points[$num++] = $tmp2; + } + } + //updating variables + $prev_node = $curr_node; + + //handling cases where the agent meets a dead end + if($num == 0){ + //If the prevoius point was not the starting point, go back to the previous node and continue + if($n>1){ + $curr_node = $route[$n-2]; + } + //If the previous node was the starting point, move in the other direction of the raod (i.e. different formt eh one chosen previously + else{ + if((int)$curr_node === (int)$row_st[0]){ + $curr_node = $row_st[1]; + } + else if((int)$curr_node === (int)$row_st[1]){ + $curr_node = $row_st[0]; + } + } + } + //If the agent does not meet a dead end + else{ + //choosing a new road randomly + $ran = rand(0,$num-1); + $curr_node = $points[$ran]; + } + } + //caluclting final route to move to the last point unitll time runs out; + $url = 'http://routes.cloudmade.com/81aa79a9504e4430a8a32f491ef96f07/api/0.3/'.$start_lat.','.$start_long.','; + if($n>0){ + $url = $url.'['; + for($i=0; $i<$n-1; $i++){ + $url = $url.$xc[$i].','.$yc[$i]; + if($i < $n-2)$url = $url.','; + } + $url = $url.'],'; + } + $url = $url.$xc[$n-1].','.$yc[$n-1].'/car.js'; + + $aContext = array( + 'http' => array( + 'proxy' => 'tcp://10.3.100.212:8080', + 'request_fulluri' => true, + 'header' => 'Accept-Charset: UTF-8, *;q=0' + ), + ); + $cxContext = stream_context_create($aContext); + //calculating shortest path + $sFile = file_get_contents($url, False, $cxContext); + //header for json content to be sent to the client + header('Content-Type: application/json'); + //printing route to be sent to the client + echo $sFile; +} +//seeding rand function +list($usec, $sec) = explode(' ', microtime()); +srand((float) $sec + ((float) $usec * 100000)); + +/*variables received via ajax request from client i.e Latitude of Start point, Longitude of start point, Latitude of destination point, Longitude of destination point, and the time available respectively */ + $start_lat = $_POST['start_lat']; + $start_lon = $_POST['start_lon']; + $dest_lat = $_POST['end_lat']; + $dest_lon = $_POST['end_lon']; + $time = $_POST['time']; + +//calling function for random motion with required parameters +random_movement($start_lat, $start_lon, $dest_lat, $dest_lon, $time); +?> Modified: sis/sandbox/gsoc2013/crimgeoprofile/save.php URL: http://svn.apache.org/viewvc/sis/sandbox/gsoc2013/crimgeoprofile/save.php?rev=1525754&r1=1525753&r2=1525754&view=diff ============================================================================== --- sis/sandbox/gsoc2013/crimgeoprofile/save.php (original) +++ sis/sandbox/gsoc2013/crimgeoprofile/save.php Tue Sep 24 00:12:22 2013 @@ -1,27 +1,24 @@ <?php -ini_set("log_errors", 1); -ini_set("error_log", "/tmp/php-error.log"); -error_log( "Hello, errors!" ); +/*This script is used saving data on the sever side. Spatia data is saved in GeoJSON format whole non-spatial data is saved as json format */ +//getting post data from client $json = $_POST['json']; - + $geojson = $_POST['geojson']; $fname = $_POST['fname']; - if (json_decode($json) != null) { /* sanity check */ - - $file = fopen($fname,'w+'); - - fwrite($file, $json); - - fclose($file); +if (json_decode($json) != null) { /* sanity check */ + //writing non-spatial datato file + $file = fopen($fname,'w+'); + fwrite($file, $json); + fclose($file); + //writng spatial data in GEOJSON format to file + $file = fopen($fname.'_geo','w+'); + fwrite($file, $geojson); + fclose($file); + //sending response to client echo "Saved"; - - } else { - - echo "Unable to Save!"; - - } - - +} else { //if snaity check fails + echo "Unable to Save!"; +} ?>
