Buffer Point API Function

Choose a distance to select tracts by

Here we demo the Buffer Point function of the api. Click here for detailed documention of the function

This Example application is using DRCOG's Census Tract Change data from the DRCOG Data Catalog.

When you click on the map a selection of Census Tracts will draw on the map and a balloon showing the population change percentage for the selected tracts between 2000 and 2010 will pop up. You can select the buffer distance of your click from the dropdown

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": {
                "tractid": "08031004303",
                "pop_2010": "4067",
                "pop_2000": "3906",
                "pop_change": "0.041219",
                "geojson": {
                    "type": "MultiPolygon",
                    "coordinates": [
                        [
                            [
                                [
                                    -11679895.22762218,
                                    4824134.026472244
                                ],
                                [
                                    -11679895.450261168,
                                    4824083.0893480955
                                ],
                                [
                                    -11679921.387702517,
                                    4824083.523470209
                                ],
                                [
                                    -11679999.311346075,
                                    4824084.970544078
                                ],
                                [
                                    -11680025.360106917,
                                    4824085.549373681
                                ],
                                [
                                    -11680051.297548277,
                                    4824085.694081092
                                ],
                                [
                                    -11680129.443830812,
                                    4824086.128203319
                                ]
                   }
             }
}

Here is a JavaScript snippet that uses ajax to call a php script and how it uses the results (php script is below)

  
 /*
 Here is the success function for my ajax call to the php script
 */

 function (data, status, xhr) {

    //see how many records are returned
    var len = parseFloat(data.total_rows);
   // if nothing is found, let them know
    if (len == 0) {
        alert("Nothing found");
          } else {
     //parse the returned json for the Population change data
                 $.each(data.rows, function (k, v) {
                        pop_change = parseFloat(data.rows[k].row.pop_change) * 100;
                        sum = sum + pop_change;
                        total = total + 1;
        });
                      var mean = sum / total;
                      mean = mean.toFixed(2);
                      mean = mean.toString();
                      mean = mean + "%";
          // clear the polygons if any exist
                      selected_tracts.destroy();
        //Add an empty vector layer to populate after the click event
                     selected_tracts = new OpenLayers.Layer.Vector("Selected Tracts");
                    map.addLayer(selected_tracts);
                    var gformat = new OpenLayers.Format.GeoJSON();
                    var gcoords = '';
        //Loop through the returned api query result and get the coordinates from geojson
                    $.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 + ']';                            
                            var gg = '{"type":"FeatureCollection", "features":' + gcoords + '}';
                            var feats = gformat.read(gg);

        //Add the new features to showcase the polygons used in the api function

                            selected_tracts.addFeatures(feats);

    }
                              //remove popup if a new is needed
                                if (currentPopup != null && currentPopup.visible()) {
                                      currentPopup.hide();
                                      currentPopup.destroy();
                                   }

                             info = new OpenLayers.Popup.FramedCloud(
                                     "data",
                                      xy_900913,
                                      null,
                                      mean , //this is where the data from api is put into the popup
                                      null,
                                     true
                                      );
                                    currentPopup = info;
                                   //add the popup to the map
                                     map.addPopup(info);
                               },
                                        

Here is the Javascript in it's entirety


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 gphy = new OpenLayers.Layer.Google(
        "Google Physical",
        {type: google.maps.MapTypeId.TERRAIN}
    );

    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 buff_dist = '5280';
$(document).ready(function () {

var currentPopup;
//Setting the projections used 
var p4326 = new OpenLayers.Projection("EPSG:4326");
var p900913 = new OpenLayers.Projection("EPSG:900913");

//All of the data in the API are in 2232 which is Colorado State Plane Central, NAD 83. We define this for Proj4js here
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");

//We are setting up the control control in OpenLayers here
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
                defaultHandlerOptions: {
                    'single': true,
                    'double': false,
                    'pixelTolerance': 4,
                    '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) {                  
                   //get the lat long from the click
                    var longlat = map.getLonLatFromPixel(e.xy);    
                   //transform the xy from google to 2232
		    var xy = new OpenLayers.LonLat(longlat.lon, longlat.lat).transform(new OpenLayers.Projection("EPSG:900913"), p2232);
                    var xy_900913 = new OpenLayers.LonLat(xy.lon, xy.lat).transform(p2232, p900913);
                           
                    id(xy);

		     function id(location) { 
                          var html, pop_change;
                          var sum = 0;
                          var total = 0;
                 
                     $.ajax({
                            // Using ajax to call the php that uses the api
                             url: "/location/to/php/script.php", 
                            // If .NET url: "/IdentifyJson", //
                            // Get XY from the click
                              data: {lat: xy.lat, lon: xy.lon, distance: buff_dist},
                              dataType: "json",                                     
                              type: "POST",
                              success:  function (data, status, xhr) {

                            //see how many records are returned
                              var len = parseFloat(data.total_rows);
                              // if nothing is found, let them know
                              if (len == 0) {
                                     alert("Nothing found");
                             } else {
                            //parse the returned json for the Population change data
                              $.each(data.rows, function (k, v) {
                                      pop_change = parseFloat(data.rows[k].row.pop_change) * 100;
                                      sum = sum + pop_change;
                                      total = total + 1;
                                      });
                                var mean = sum / total;
                                mean = mean.toFixed(2);
                                mean = mean.toString();
                                mean = mean + "%";
                            // clear the polygons if any exist
                                selected_tracts.destroy();
                         //Add an empty vector layer to populate after the click event
                                selected_tracts = new OpenLayers.Layer.Vector("Selected Tracts");
                                map.addLayer(selected_tracts);
                                var gformat = new OpenLayers.Format.GeoJSON();
                                var gcoords = '';
                          //Loop through the returned api query result and get the coordinates from geojson
                        $.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 + ']';                            
                                var gg = '{"type":"FeatureCollection", "features":' + gcoords + '}';
                               var feats = gformat.read(gg);

        //Add the new features to showcase the polygons used in the api function
                            selected_tracts.addFeatures(feats);

    }
                              //remove popup if a new is needed
                                if (currentPopup != null && currentPopup.visible()) {
                                      currentPopup.hide();
                                      currentPopup.destroy();
                                   }

                             info = new OpenLayers.Popup.FramedCloud(
                                     "data",
                                      xy_900913,
                                      null,
                                      mean , //this is where the data from api is put into the popup
                                      null,
                                     true
                                      );
                                    currentPopup = info;
                                   //add the popup to the map
                                     map.addPopup(info);
                               }

                    //if nothing is returned from the click return an alert
                           error: function(xhr, status, error) {
                                   $().trigger("ajax:failure", [xhr, status, error]);
                                    if (xhr.status == 404) { 
                                         alert("nothing found");
                                      }      
                                   }
                               });              
                          }                                                              
                      }                  
                 })
          

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

PHP example


    //get the lat long from the click event
   $lat = $_POST["lat"];
   $long = $_POST["lon"];

   //set up the url for the restful web service call
   $base_url = "http://gis.drcog.org/REST/v1/ws_geo_bufferpoint?";
   $srid = '2232';
   $geotable = "census_change_2000_2010_tracts";
   //Postgis' ST_AsGeoJson function give us the ability to have the api return geojson coordinates that OpenLayers can use to draw the features

   //Let PostGIS take care of the reprojection as well with ST_Transform
   $fields = "tractid,pop_2010,pop_2000,pop_change,ST_AsGeoJson (ST_Transform(the_geom, 900913)) as geojson";
   $encodefields = urlencode($fields);

   //get the distance parameter from the dropdown box 
   $distance = $_POST["distance"];
   $limit = '10';
   $format = 'json';
   $parameters = NULL;
   $values =  "parameters=".$parameters."&distance=".$distance."&format=".$format."&fields=".$encodefields."&geotable=".$geotable."&srid=".$srid."&y=".$lat."&x=".$long."&limit=".$limit;
   $str_values = (string)$values; 
   $url = $base_url.$str_values;

   //call the webservice
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);     
   $data = curl_exec($curl);
   $data = $data;

   //send the json response to browser

   echo $data;

C# Example


public JsonResult BufferpointJson(string lat, string lon, string distance)
        {
            var base_url = "http://gis.drcog.org/REST/v1/ws_geo_bufferpoint.php?";
            var url_param = "distance={0}&fields={1}&geotable={2}&srid={3}&limit={4}&parameters={5}&x={6}&y={7}&format={8}";
            var srid = "2232";
            var geotables = "census_change_2000_2010_tracts";
            var fields = "tractid,pop_2010,pop_2000,pop_change,ST_AsGeoJson (ST_Transform(the_geom, 900913)) as geojson";
            var format = "json";
            var limit = 10;
            var parameters = String.Empty;
            string url = String.Format(base_url + url_param
                , distance, fields, geotables, srid, limit
                , parameters, lon, lat, 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()))
                {
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    result = reader.ReadToEnd();
                }
            }
            return Json(result, "text/x-json", JsonRequestBehavior.AllowGet);
        }