AnsweredAssumed Answered

Selection to Grid

Question asked by Linn_GIS on Mar 13, 2015
Latest reply on Mar 13, 2015 by jskinner-esristaff

Seeking assistance on getting a freehand selection to push objects to a grid. Thanks,

 

 

<!DOCTYPE html> 

<html> 

  <head> 

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 

    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"> 

    <title>Title</title> 

    <link rel="stylesheet" href="http://js.arcgis.com/3.10/js/dojo/dijit/themes/claro/claro.css"> 

    <link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">

  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

 

 

 

 

    <style> 

      #mapDiv { 

        padding: 0; 

        margin: 0; 

      } 

 

    

  html, body {

  height: 100%;

  width: 100%;

  margin: 0;

  padding: 0;

   text-align: left;

}

body {

  background-color: #FFF;

  overflow: hidden;

  font-family: "Trebuchet MS";

}

#bcMain {

  width: 100%;

  height: 100%;

}

#divRenderer {

  position: absolute;

  left: 27px;

  bottom: 27px;

}

#cpBottom {

  height: 100px;

 

}

#divGrid {

  height: 100%;

}

.dgrid {

  border: none;

}

.field-eqid {

  width: 100px;

}

.field-datetime {

  width: 160px;

}

.field-magnitude {

  width: 60px;

}

.field-longitude {

  width: 100px;

}

.field-latitude {

  width: 100%;

}

 

 

  .esriControlsBR{

     display: none;

    }

.esriPopup .esriPopupVisible { display: none;}

 

.esriPopupWrapper{ display: none;}

 

 

.tundra .dijitBorderContainer-dijitContentPane {

background-color: rgb(16, 100, 95);

height: 58px;

overflow: hidden;

}

 

 

.commandPanel {

  height: 52px;

  margin: 0px;

  padding: 2px;

  overflow: hidden;

  position: absolute;

  text-align: center;

  vertical-align: middle;

  }

  

 

 

  .okIE .commandButton {

  border-radius: 8px;

  }

  .commandButton {

  width: 44px;

  height: 44px;

  text-align: center;

  cursor: pointer;

  }

  .appTheme {

  color: rgb(255, 255, 255);

  background-color: rgb(16, 100, 95);

  }

 

 

  .commandPanel table {

  border-spacing: 0px;

  }

 

 

  .commandIcon {

  width: 32px;

  height: 32px;

  margin-top: 6px;

  }

 

 

#divBuff {

  width: 200px;

  max-height: 424px;

  padding: 4px;

  position: absolute;

  display: none;

  background-color: rgb(16, 100, 95);

  right: 7px;

  top: 1%;

  z-index: 999;

  border-radius: 8px;

  color: rgb(255, 255, 255);

  vertical-align: middle;

  text-align: center;

  border-color: 1px solid #121310;

  text-align:left;

  }

#appIcon {

   float: left;

   border: none;

   border-style: none;

   vertical-align: middle;

   max-height: 95%;

   margin: 5px;

  }

 

 

.titleText {

  height: 48px;

  margin: 4px;

  padding: 0px;

  font-size: 175%;

  vertical-align: middle;

  word-wrap: break-word;

  float: left;

  }

 

 

  #divLayers {

  width: 421px;

  height: 290px;

  padding: 4px;

  position: absolute;

  display: none;

  background-color: rgb(16, 100, 95);

  right: 7px;

  top: 1%;

  z-index: 999;

  border-radius: 8px;

 

  }

  .layersBox {

  width: 400px;

  max-height: 270px;

  padding: 4px;

  position: absolute;

 

  background-color: rgb(16, 100, 95);

  right: 7px;

  top: 1%;

  z-index: 999;

  border-radius: 8px;

  color: white;

  vertical-align: middle;

  text-align: left;

  border-color: 1px solid #121310;

  overflow-y: scroll;

    overflow-x:hidden;

  padding: 4px;

  z-index: 40;

  word-wrap: break-word;

  }

#divTableSearch {

  width: 75%;

  height: 175px;

  padding: 4px;

  position: absolute;

  right: 50px;

  display: none;

  background-color: rgb(16, 100, 95);

  Bottom: 1%;

  z-index: 999;

  border-radius: 8px;

  vertical-align: middle;

  }

 

 

/* this line hides layers when out of scale for the inline TOC */

        .agsjsTOCOutOfScale {

            display: none

        }

 

 

 

    </style>

 

  <script type="text/javascript">

        var djConfig = {

            parseOnLoad: true,

            packages: [{

                "name": "agsjs",

                "location": "http://gmaps-utility-gis.googlecode.com/svn/tags/agsjs/latest/build/agsjs"

            }]

        };

    </script>

 

 

  <script>

  $(document).ready(function(){

  $("#Search").click(function(){

  $("#divBuff").fadeToggle("fast");

  $("#divTableSearch").fadeToggle("fast");

  });

 

 

  });

 

 

</script>

 

 

  <script src="http://js.arcgis.com/3.10/"></script> 

  

  <script> 

   var toc;

   require([ 

  "esri/map",

  "esri/layers/FeatureLayer", 

  "esri/tasks/query",

  "esri/geometry/Circle", 

  "esri/graphic",

  "esri/InfoTemplate",

  "dojo/_base/connect",

"agsjs/dijit/TOC",

  "esri/layers/ArcGISDynamicMapServiceLayer",

"esri/dijit/Legend",

"dijit/registry",

    "esri/dijit/Legend", "esri/tasks/GeometryService", "esri/tasks/BufferParameters", "dijit/form/Button",

    "esri/geometry/Extent", "esri/graphicsUtils", "esri/toolbars/draw",

  "dojo/dom-construct",

  "esri/symbols/SimpleMarkerSymbol", 

  "esri/symbols/SimpleLineSymbol",

  "esri/symbols/SimpleFillSymbol",

  "esri/renderers/SimpleRenderer", 

  "esri/config",

  "esri/Color",

  "dojo/dom",

  "dojo/parser",

  "dojo/store/Memory",

  "dojo/data/ItemFileWriteStore",

  "dgrid/OnDemandGrid",

  "dojox/grid/EnhancedGrid",

  "dojox/grid/enhanced/plugins/exporter/CSVWriter",

  "dojox/grid/enhanced/plugins/Printer",

  "dgrid/Selection",   

  "dijit/layout/BorderContainer",

  "dijit/layout/ContentPane",

  "dojo/_base/declare",

  "dojo/_base/array",

  "dojo/on",

  "dijit/form/ComboBox",

  "dojo/domReady!"],

  function( 

  Map,

  FeatureLayer, 

  Query,

  Circle, 

  Graphic,

  InfoTemplate,

  connect,TOC, ArcGISDynamicMapServiceLayer,Legend,

  registry,  Legend, GeometryService, BufferParameters,

      Extent, Button, graphicsUtils, Draw, domConstruct,

  SimpleMarkerSymbol, 

  SimpleLineSymbol,

  SimpleFillSymbol,

  SimpleRenderer, 

  esriConfig,

  Color,

  dom,

  parser,

  Memory,

  ItemFileWriteStore,

  Grid,

  EnhancedGrid,

  CSVWriter,

  Printer,

  Selection,

  BorderContainer,

  ContentPane,

  declare,

  array,

  on

   ) { 

 

    var map, gsvc, selectionToolbar, tb;

  

 

 

    // Parse DOM nodes decorated with the data-dojo-type attribute

    parser.parse();

 

 

 

 

 

 

    console.log(registry.byId("zoomin"));

 

 

    // Initialize the dgrid

    var gridNF = new EnhancedGrid({

      structure : [

      

        {name: "name", field : "Name"},

        {name: "requesttype", field : "Request Type"},

        {name: "requestreceived", field : "Request Received"}

 

      ],

   plugins: {

            exporter: true,

       printer: true

        }

    }, "divGrid");

  gridNF.startup();

 

      //Step: Specify the output fields

    

    var outFieldsNF = ["objectid", "name", "requesttype", "requestreceived"];

 

        // this should not be needed as nearly all query & select functions are performed on the client 

       // esriConfig.defaults.io.proxyUrl = "/proxy"; 

 

        map = new Map("mapDiv", { 

          basemap: "gray", 

          center: [-96.000, 33.699], 

          zoom: 4, 

          slider: true 

        }); 

 

    map.on("load", initSelectToolbar);

    map.on("load", initToolbar);

 

 

   var markerSymbol = new SimpleMarkerSymbol( 

          SimpleMarkerSymbol.STYLE_CIRCLE,  12, 

          new SimpleLineSymbol( SimpleLineSymbol.STYLE_NULL, new Color([100, 34, 250, 0.9]),1  ),  new Color([255, 34, 25, 0.9]) 

        ); 

 

 

 

    var fieldsSelectionSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,

    new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,

    new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.5]));

 

 

    var extentSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,

    new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,

    new Color([255, 0, 0]), 2), new Color([84, 84, 84, 0.5]));

 

 

 

 

 

 

 

        // Note that an info template has been defined so when 

 

        //selected features are clicked a popup window will appear displaying the content defined in the info template. 

        var featureLayer = new FeatureLayer("http://sampleserver6.arcgisonline.com/arcgis/rest/services/LocalGovernment/CitizenRequests/MapServer/0",{ 

         // infoTemplate: new InfoTemplate("Hospitals: ${NAME}", "${*}"), 

          outFields: ["objectid", "name", "requestreceived", "requesttype"], 

          mode: FeatureLayer.MODE_ONDEMAND 

        });

       

    featureLayer.setSelectionSymbol(markerSymbol); 

  map.addLayer(featureLayer);

 

  countyLayer = new ArcGISDynamicMapServiceLayer("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer", {

      });

   countyLayer.setVisibility(true);

  

  

   //add the legend

    map.on("layers-add-result", function (evt) {

        var layerInfo = arrayUtils.map(evt.layers, function (layer, index) {

            return {

                layer: layer.layer,

                title: layer.layer.name

            };

        });

        if (layerInfo.length > 0) {

            var legendDijit = new Legend({

                map: map,

                layerInfos: layerInfo

            }, "legendDiv");

            legendDijit.startup();

        }

 

 

        //add check boxes

        arrayUtils.forEach(layerInfo, function (layer) {

            var layerName = layer.title;

            if (layerName == undefined) {   layerName = "SSSI";  }

         

            var checkBox = new CheckBox({

                name: "checkBox" + layer.layer.id,

                value: layer.layer.id,

                checked: layer.layer.visible,

                onChange: function (evt) {

                    var clayer = map.getLayer(this.value);

                    clayer.setVisibility(!clayer.visible);

                    this.checked = clayer.visible;

                }

            });

            //add the check box and label to the TOC

            domConstruct.place(checkBox.domNode, "toggle",

                "after");

            var checkLabel = domConstruct.create('label', {

                'for': checkBox.name,

                innerHTML: layerName

            }, checkBox.domNode, "after");

            domConstruct.place("<br/>", checkLabel,

                "after");

        });

    });

  

  // map.addLayer(countyLayer);

   map.addLayers([ featureLayer, countyLayer]);

 

  //Add Table of Contents

 

 

 

 

  ///////////////////////////////////////////////////////////////////////////////////

 

 

    on(dom.byId("selectPolygonButton"), "click", function () {

        selectionToolbar.activate(Draw.EXTENT);

    });

 

 

    on(dom.byId("selectCircleButton"), "click", function () {

        selectionToolbar.activate(Draw.CIRCLE);

    });

 

 

    on(dom.byId("selectFreehandPolygonButton"), "click", function () {

        selectionToolbar.activate(Draw.FREEHAND_POLYGON);

    });

 

 

    on(dom.byId("clearSelectionButton"), "click", function () {

        featureLayer.clearSelection();

      

        map.graphics.clear();

        dom.byId("messages").innerHTML = "<a>No features selected</a>";

    });

////////////////////////////////////////////////

    function initSelectToolbar(event) {

               alert("initSelectToolbar ");

          selectionToolbar = new Draw(event.map);

          var selectQuery = new Query();

 

 

          on(selectionToolbar, "DrawEnd", function (geometry) {

            var promises = [];

            var graphic = new Graphic(geometry, extentSymbol);

            console.log(graphic);

            map.graphics.add(graphic);

            selectionToolbar.deactivate();

            selectQuery.returnGeometry = false;

            selectQuery.outFields = ["*"];

            selectQuery.geometry = geometry;

            if(featureLayer.visible){

              promises.push(featureLayer.selectFeatures(selectQuery, FeatureLayer.SELECTION_NEW));

            }

          

            var allPromises = new All(promises);

            allPromises.then(function (r) {

              showselResults(r);

            });

          });

 

 

 

 

        }

       

////////////////////////////////////////////////////       

       

gsvc = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

 

 

    function initToolbar(evtObj) {

        alert("initToolbar ");

        app.tb = new Draw(evtObj.map);

        app.tb.on("draw-end", doBuffer);

    }

 

        // selection symbol used to draw the selected census block points within the buffer polygon 

     

      //  map.addLayer(featureLayer); 

         

      //  var circleSymb = new SimpleFillSymbol(SimpleFillSymbol.STYLE_NULL,new SimpleLineSymbol( 

     //       SimpleLineSymbol.STYLE_SHORTDASHDOTDOT, 

     //       new Color([105, 105, 105]), 3 ), new Color([255, 255, 0, 0.25]) 

     //   ); 

 

 

     //   var circle; 

     //   var radius = parseInt(dom.byId("bufferDistance").value); 

 

        //when the map is clicked create a buffer around the click point of the specified distance. 

    //    map.on("click", function(evt){ 

    //      var radius = parseInt(dom.byId("bufferDistance").value); 

   //       circle = new Circle({ 

   //         center: evt.mapPoint, 

//  //         geodesic: true, 

  //          radius: radius, 

  //          radiusUnit: "esriMiles" 

  //        });  ; 

 

     //     map.graphics.clear(); 

  //        map.infoWindow.show(); 

           

  //        var graphic = new Graphic(circle, circleSymb); 

  //        map.graphics.add(graphic); 

 

//         var query = new Query(); 

//          query.geometry = circle.getExtent(); 

//          //use a fast bounding box query. will only go to the server if bounding box is outside of the visible map 

//          featureLayer.queryFeatures(query, selectInBuffer); 

  //      }); 

 

 

 

 

   //     function selectInBuffer(response){ 

  //        var feature; 

  //        var features = response.features; 

  //        var inBuffer = []; 

 

          //filter out features that are not actually in buffer, since we got all points in the buffer's bounding box 

 

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

//           feature = features[i]; 

//           if(circle.contains(feature.geometry)){ 

//             inBuffer.push(feature.attributes[featureLayer.objectIdField]); 

//           } 

//         } 

 

//         var query = new Query(); 

//         query.objectIds = inBuffer; 

          //use a fast objectIds selection query (should not need to go to the server) 

 

//         featureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function(results){                         

//           var totalFeatures = results.length; 

//           var r = ""; 

//           r = "<b>The total Number of Nursing Homes within the Buffer  <i>" + totalFeatures+ "</i>.</b>"; 

//           dom.byId("messages").innerHTML = r; 

//         }); 

  

//  populateGrid(response);

//        } 

 

    

      //Step: Wire the layer's selection complete event

      

      //FeatureLayer.on("selection-complete", populateGrid);

      

      // Step: Perform the selection

      

      //FeatureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW);

 

 

 

        function showselResults(results) {

          var rsltsMsg = "";

          rsltsMsg = 'Total features selected:  <b>[count]</b><br>  ';

          var rsltCnt = 0;

          if(featureLayer.visible){

            rsltsMsg += 'FeatureLayer 1:  <b>' + results[rsltCnt].length.toString() + '</b><br> &nbsp';

            rsltCnt++;

          }

         

          var count = 0;

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

            count += results[i].length;

          }

 

 

          dom.byId("messages").innerHTML = rsltsMsg.replace('[count]', count);

        }

 

 

 

 

    function populateGrid(results) {

 

 

      var gridData;

 

 

      dataNF = array.map(results.features, function(feature) {

        return {

         

           // Step: Reference the attribute field values

         

          "objectid" : feature.attributes[outFieldsNF[0]],

          "name" : feature.attributes[outFieldsNF[1]],

          "requesttype" : feature.attributes[outFieldsNF[2]],

          "requestreceived" : feature.attributes[outFieldsNF[3]]

 

 

        }

      });

 

      // Pass the data to the grid

      var memStore = new ItemFileWriteStore({

        data : {

   identifier: 'OBJECTID',

   items: dataNF

  }

      });

  

      gridNF.setStore(memStore);

    }

 

  on(dojo.byId("exportAll"), "click", function () {

 

  gridNF.exportGrid("csv", function(str){

  alert(str);

  });

  });

 

  on(dojo.byId("printAll"), "click", function () {

  gridNF.printGrid({title: "Hospital List", cssFiles: []});

  });

 

 

   function doBuffer(evtObj) {

        var geometry = evtObj.geometry,

            map = app.map,

            gsvc = app.gsvc;

        switch (geometry.type) {

            case "point":

                var symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 0, 0]), 1), new Color([0, 255, 0, 0.25]));

                break;

            case "polyline":

                var symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color([255, 0, 0]), 1);

                break;

            case "polygon":

                var symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_NONE, new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25]));

                break;

        }

 

 

  var graphic = new Graphic(geometry, symbol);

  map.graphics.add(graphic);

 

 

  //setup the buffer parameters

  var params = new BufferParameters();

  params.distances = [dom.byId("distance").value];

 

 

  params.unit = GeometryService[dom.byId("unit").value];

 

 

  if (geometry.type === "polygon") {

  //if geometry is a polygon then simplify polygon.  This will make the user drawn polygon topologically correct.

  gsvc.simplify([geometry], function (geometries) {

  params.geometries = geometries;

  gsvc.buffer(params, showBuffer);

  });

  } else {

  params.geometries = [geometry];

  gsvc.buffer(params, showBuffer);

  }

  }

 

 

  function showBuffer(bufferedGeometries) {

  var symbol = new SimpleFillSymbol(

  SimpleFillSymbol.STYLE_SOLID,

  new SimpleLineSymbol(

  SimpleLineSymbol.STYLE_SOLID,

  new Color([255, 0, 0, 0.65]), 2),

  new Color([255, 0, 0, 0.35]));

 

 

  arrayUtils.forEach(bufferedGeometries, function (geometry) {

  var graphic = new Graphic(geometry, symbol);

  app.map.graphics.add(graphic);

  });

  app.tb.deactivate();

  app.map.showZoomSlider();

  }

 

 

 

 

 

 

  app = {

  map: map,

  tb: tb,

  gsvc: gsvc

  };

 

 

 

 

      });  

    </script> 

  </head> 

   

   <body class="claro">

   <div data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline'"  style="width:100%;height:100%;margin:0;">

      <div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top'" style="height:40px;">

   <div id="appTitle" style= "vertical-align: middle; padding-left: 20px">

 

  

 

 

   <span class="titleText" style="color:white;">Title</span>

 

  <div id="commandPanel" class="commandPanel" style="right: 4px; top:4px;">

 

  <table class="appTheme">

  <tbody>

  <tr>

  <td class="commandPanelItem"><div id="Search" class="commandButton appTheme appThemeHover" title="Find" style="display: block; visibility: visible;"><img src="http://webhelp.esri.com/arcgisexplorer/1500/gpsicons/GPX_107_air_strip.png" class="commandIcon"></div></td>

 

  </tr>

  </tbody>

  </table>

 

  </div>  <!-- ENd HEADER -->

  </div>

  </div>

 

 

  <div id="mapDiv" data-dojo-props="region:'center'" data-dojo-type="dijit/layout/ContentPane" style="border:1px solid #000;">

 

  <div id="divBuff" class="searchBox appTheme" style="right: 2px; top: 2px; bottom: 2px;">

  <label for="searchBox_entry">Buffer Tools   </label>

  <span id="drop"><form name="FormSelection">

  <!--  <select name="selection" onChange="selecteduser()">  -->

  <select name="BufferSelection">

  <option> Layer 1</option>

 

 

  </select>

  </form> </span>

 

  <br/><br/>

  <span id="messages"></span>

  <br/>

  

 

   <div><b>Feature Selection</b></div>

      <button id="selectPolygonButton" data-dojo-type="dijit/form/Button">Polygon</button>

      <button id="selectCircleButton" data-dojo-type="dijit/form/Button">Circle</button>

      <button id="selectFreehandPolygonButton" data-dojo-type="dijit/form/Button">Freehand Polygon</button>

      <button id="clearSelectionButton" data-dojo-type="dijit/form/Button">Clear Selection</button>

      <br /><hr />

 

    <button id="exportAll">Export all to CSV</button>

  <button id="printAll">Print All</button>

  </div> <!-- End BufferDiv  -->

 

  </div>

 

 

  <div id="divLayers">

  <div id="layersBox" class="layersBox appTheme" style="right: 2px; top: 2px; display: block;">

 

  <div id="divLayersTitle">Toggle Visible Layers:</div>

 

 

  </div>

 

  </div> <!-- End divLayers -->

  <div id="divTableSearch" align="center">

 

  <div id="divGrid"style="height:110px;">

  </div> <!-- End divGrid  -->

 

  </div> <!-- End divTableSearch -->

 

</div><!-- End Map Div  -->

 

   </div><!--Headline -->

 

 

  </body> 

</html> 

Outcomes