Buffer Feature API function

Choose a bike path type to show auto-bike crashes by

Number of Crashes near bike path type is

Here we demo the Buffer Feature function of the api. Click here for detailed documentation of the function

This Example application is using DRCOG's Bicyle Facility Inventory and Arapahoe County Crash Points from the DRCOG Data Catalog.

When you chose a bike path type from the drop down, the application uses the Buffer Feature function to do a spatial query on our crash data and return crash points near the path type.

Example URL: http://gis.drcog.org/REST/v1/ws_geo_bufferpoint.php?parameters=&distance=5280&format=json&fields=tractid,pop_2010,pop_2000,pop_change,ST_AsGeoJson+(ST_Transform(the_geom,+900913))+as+geojson&geotable=census_change_2000_2010_tracts&srid=2232&y=1723770.9398516985&x=3130084.2959892196&limit=10


{ 
    "total_rows": "1",
    "rows": [
        {
            "row": {
                "gid": "2419",
                "loc_01": "SOUTH HOLLY STREET",
                "loc_02": "EAST YALE AVENUE",
                "geojson": {
                    "type": "Point",
                    "coordinates": [
                        -11679716.671284003,
                        4817754.292591304
                    ]
                }
            }
        }
    ]
}

Here is the a sample php script that receives the bike path type from the drop down. This script is putting together a url with the required parameters to send off to the server. The response comes back as json and we get our answer

Here is a JavaScript that uses ajax to call the above php script and how it uses the results. The ajax is kicked off when the user selects the bike path type from the drop down


function findCrashes(){
     //getting the value needed from the drop down menu
    path_type = $("#selectdistance").val();

    $.ajax({

                                     url: '/location/of/php/crashes.php', 
                                     data: {path_type: path_type},
                                     dataType: "json",
                                     type: "POST",
                                     success: function(data, status, xhr) {
                                             //parse the returned json to get the number of crashes
                                             var len = parseFloat(data.total_rows);
                                           
                                             var crash_number = len.toString();
                                             //Use jquery to show the number of crashes by bike route type
                                             $("#crash_number").html(crash_number);
                                             $("#path_type").html($("#selectdistance option:selected").text());
                                             //remove crash points if they're there alread
                                             crash_sites.destroy();
                                             //create new vector layer in OpenLayers 
                                             crash_sites = new OpenLayers.Layer.Vector("Crash Locations",
                                                                                 {styleMap: styleMap});
                                             map.addLayer(crash_sites);
                                             var p = new OpenLayers.Format.GeoJSON();
                                             var gformat = new OpenLayers.Format.GeoJSON();    					    
                                             var gcoords= " ";
                                             //iterate through each record in the returned json to get the coordinates to place on the map
                                             $.each(data.rows, function(k, v) {
                                                 var last = len - 1; 
                                                 var coords = JSON.stringify(data.rows[k].row.geojson);
                                                 if (k < last){
                                                 gcoords += '{"geometry":'+coords+'},';
                                                 }
                                                 else{ 
                                                 gcoords += '{"geometry":'+coords+'}';
                                                 }
                                               });  
                                             gcoords = '['+gcoords+']';
                                             //create the json that OpenLayers likes for a geojson vector layer
      					     var gg = '{"type":"FeatureCollection", "features":' + gcoords + '}'; 
                                             var feats = gformat.read(gg);   
                                            //add to the map                                       
                                             crash_sites.addFeatures(feats);                                              
                                             },

                                     error: function(xhr, status, error) {
                                       $().trigger("ajax:failure", [xhr, status, error]); 
                                             alert(error);                                       
                                        }                       
                          });
}

Here all of the javascript used in this example


var map; 

$(document).ready(function () {
  
    map = new OpenLayers.Map('map', {
	maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
         maxResolution: 156543.0399,
      numZoomLevels: "auto",
         units: 'm',
         projection: new OpenLayers.Projection("EPSG:4326"),
         displayProjection: new OpenLayers.Projection("EPSG:900913")
	});
	
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    
    var gmap = new OpenLayers.Layer.Google(
        "Google Streets", 
        {numZoomLevels: 20}
    );

    var ghyb = new OpenLayers.Layer.Google(
        "Google Hybrid",
        {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20}
    );
    var gsat = new OpenLayers.Layer.Google(
        "Google Satellite",
        {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22}
    );
    
     map.addLayers([gmap, gphy, ghyb, gsat]);

      map.setCenter(new OpenLayers.LonLat(-104.96, 39.75).transform(
        new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()), 9);
});

var path_type;
//create an empty vector layer that we will fill in later
var crash_sites = new OpenLayers.Layer.Vector("Crash Locations");
//create a simple OpenLayers style that uses a flashing gif image for the crash points
var style = new OpenLayers.Style({
  'pointRadius': 6,
  'externalGraphic': 'location/of/gif/image.gif'
});
//initialize the style
var styleMap = new OpenLayers.StyleMap(style);

$(document).ready(function () {

//set the rpojections used in the app
var p4326 = new OpenLayers.Projection("EPSG:4326");
var p900913 = new OpenLayers.Projection("EPSG:900913");

crash_sites = new OpenLayers.Layer.Vector("Crash Locations",
                                               {styleMap: styleMap});

//Set up local projection 
Proj4js.defs["EPSG:2232"] = "+proj=lcc +lat_1=39.75 +lat_2=38.45 +lat_0=37.83333333333334 +lon_0=-105.5 +x_0=914401.8288036576 +y_0=304800.6096012192 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs"; 

var p2232 = new OpenLayers.Projection("EPSG:2232");

//Add the bike facility wms from the Data Catalog
var wms = new OpenLayers.Layer.WMS("Bicycle Faclities",
		"http://gis.drcog.org/geoserver/wms?", 
		{layers: 'DRCOGPUB:bicycle_facility_overview',
		 format: 'image/png',
		 transparent: 'true',
		 isBaseLayer: 'false',
		 projection: 'EPSG:2232',
		 reproject: 'true'
		});

    map.addLayer(wms);  

});

//define the function that utilizes the api
function findCrashes(){
     //getting the value needed from the drop down menu
    path_type = $("#selectdistance").val();

    $.ajax({

                                     url: '/location/of/php/crashes.php', 
                                     data: {path_type: path_type},
                                     dataType: "json",
                                     type: "POST",
                                     success: function(data, status, xhr) {
                                             //parse the returned json to get the number of crashes
                                             var len = parseFloat(data.total_rows);
                                           
                                             var crash_number = len.toString();
                                             //Use jquery to show the number of crashes by bike route type
                                             $("#crash_number").html(crash_number);
                                             $("#path_type").html($("#selectdistance option:selected").text());
                                             //remove crash points if they're there alread
                                             crash_sites.destroy();
                                             //create new vector layer in OpenLayers 
                                             crash_sites = new OpenLayers.Layer.Vector("Crash Locations",
                                                                                 {styleMap: styleMap});
                                             map.addLayer(crash_sites);
                                             var p = new OpenLayers.Format.GeoJSON();
                                             var gformat = new OpenLayers.Format.GeoJSON();    					    
                                             var gcoords= " ";
                                             //iterate through each record in the returned json to get the coordinates to place on the map
                                             $.each(data.rows, function(k, v) {
                                                 var last = len - 1; 
                                                 var coords = JSON.stringify(data.rows[k].row.geojson);
                                                 if (k < last){
                                                 gcoords += '{"geometry":'+coords+'},';
                                                 }
                                                 else{ 
                                                 gcoords += '{"geometry":'+coords+'}';
                                                 }
                                               });  
                                             gcoords = '['+gcoords+']';
                                             //make the json geojson
      					     var gg = '{"type":"FeatureCollection", "features":' + gcoords + '}'; 
                                             var feats = gformat.read(gg);   
                                            //add to the map                                       
                                             crash_sites.addFeatures(feats);                                              
                                             },

                                     error: function(xhr, status, error) {
                                       $().trigger("ajax:failure", [xhr, status, error]); 
                                             alert(error);                                       
                                        }                       
                          });
}

PHP example


   //set up the url to send to the server
   $base_url = "http://gis.drcog.org/REST/v1/ws_geo_bufferfeature.php?";
   $srid = '2232';
   $from_geotable = "bicycle_facility_overview";
   $to_geotable = "drcog_crash_2006";

   //Again using PostGIS' ST_AsGeoJson function to returne coordinates and the ST_Transform to do the reprojection
   $fields = "t.gid,t.loc_01,t.loc_02,ST_AsGeoJson (ST_Transform(t.the_geom, 900913)) as geojson";
   $encodefields = urlencode($fields);
   $distance = 250;

   //Get the bike path type from the dropdown menu\
   $path_type = $_POST["path_type"];
   $format = 'json';
   $parameters = "t.acctype='15' and type_fx_no=".$path_type;
   $urlparams = urlencode($parameters);
   $values =  "from_geotable=".$from_geotable."&to_geotable=".$to_geotable."&distance=".$distance."&format=".$format."&fields=".$encodefields."&srid=".    $srid."&parameters=".$urlparams;
   $str_values = (string)$values; 
   $url = $base_url.$str_values;

   //send off the url
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);     
   $data = curl_exec($curl);
   echo $data; 

C# Example


public JsonResult BufferfeatureJson(string fields, string parameters)
        {
            var base_url = "http://gis.drcog.org/REST/v1/ws_geo_bufferfeature.php?";
            // from_geotable=bicycle_facility_overview
            //  &to_geotable=drcog_crash_2006
            //  &distance=250
            //  &format=json
            //  &fields=t.gid,t.loc_01,t.loc_02,ST_AsGeoJson%20(ST_Transform(t.the_geom,%20900913))%20as%20geojson
            //  &srid=2232
             &parameters=t.acctype='15'%20and%20type_fx_no=4
            var url_param = "distance={0}&fields={1}&from_geotable={2}&to_geotable={3}&srid={4}&parameters={5}&format={6}";
            var srid = "2232";
            var from_geotable = "bicycle_facility_overview";
            var to_geotable = "drcog_crash_2006";
            var fields = "t.gid,t.loc_01,t.loc_02,ST_AsGeoJson (ST_Transform(t.the_geom, 900913)) as geojson";
            var format = "json";
            var distance = 250;
            string url = String.Format(base_url + url_param
                , distance, fields, from_geotable, to_geotable
                , srid, parameters, format);
            string result;
            // Create the web request  
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "application/json; charset=utf-8";
            // Get response
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
            }
            return Json(result, "text/x-json", JsonRequestBehavior.AllowGet);
        }