Select to view content in your preferred language

Query results to table

2294
4
Jump to solution
06-14-2017 03:49 PM
JamesMitchell4
Deactivated User

Hello,

Please could somebody point me in the direction of an example to show the results of a query task in a table?

I have used the find task example and it is returning results but i dont think they are in the correct format.

I will add further information tomorrow but if there is a sample code somewhere it would be great.

Thank you!

0 Kudos
1 Solution

Accepted Solutions
RobertScheitlin__GISP
MVP Emeritus

James,

   Well if you have started with that info I would have given a different sample.

Here is one using dojo dgrid:

Now that you question has been answered twice, be sure to mark this thread as answered and start a new one for further questions.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  <title>Map with a Dojo dGrid</title>

  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dojo/resources/dojo.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dgrid/css/dgrid.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dgrid/css/skins/tundra.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dijit/themes/tundra/tundra.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/esri/css/esri.css">
  <style>
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #container {
      height: 100%;
      visibility: hidden;
    }

    #bottomPane {
      height: 200px;
    }

    #grid {
      height: 100%;
    }

    .dgrid {
      border: none;
    }

    .field-id {
      cursor: pointer;
    }
  </style>

  <script src="http://js.arcgis.com/3.20/"></script>
  <script>
    // load dgrid, esri and dojo modules
    // create the grid and the map
    // then parse the dijit layout dijits
    require([
      "dojo/ready",
      "dgrid/OnDemandGrid",
      "dgrid/Selection",
      "dojo/store/Memory",
      "dojo/_base/array",
      "dojo/dom-style",
      "dijit/registry",
      "esri/map",
      "esri/layers/FeatureLayer",
      "esri/symbols/SimpleFillSymbol",
      "esri/tasks/QueryTask",
      "esri/tasks/query",
      "esri/dijit/PopupTemplate",
      "esri/InfoTemplate",
      "dojo/_base/declare",
      "dojo/number",
      "dojo/on",
      "dojo/_base/lang",
      "dojo/parser",
      "dijit/layout/BorderContainer",
      "dijit/layout/ContentPane"
    ], function(
      ready,
      Grid,
      Selection,
      Memory,
      array,
      domStyle,
      registry,
      Map,
      FeatureLayer,
      SimpleFillSymbol,
      QueryTask,
      Query,
      PopupTemplate,
      InfoTemplate,
      declare,
      dojoNum,
      on,
      lang,
      parser
    ) {
      ready(function() {

        parser.parse();

        // create the dgrid
        window.grid = new(declare([Grid, Selection]))({
          // use Infinity so that all data is available in the grid
          bufferRows: Infinity,
          columns: {
            "id": "ID",
            "stateName": "State Name",
            "median": {
              "label": "Median Net Worth",
              "formatter": dojoNum.format
            },
            "over1m": {
              "label": "Households Net Worth > $1M",
              "formatter": dojoNum.format
            }
          }
        }, "grid");
        // add a click listener on the ID column
        grid.on(".field-id:click", selectState);

        window.map = new Map("map", {
          basemap: "gray",
          center: [-101.426, 42.972],
          zoom: 4
        });

        window.statesUrl = "http://server.arcgisonline.com/ArcGIS/rest/services/Demographics/USA_Median_Net_Worth/MapServer/4";
        window.outFields = ["OBJECTID", "NAME", "MEDNW_CY", "MEDNETWORTH_pct_USAvg"];

        var fl = new FeatureLayer(window.statesUrl, {
          id: "states",
          mode: 1, // ONDEMAND, could also use FeatureLayer.MODE_ONDEMAND
          outFields: window.outFields
        });

        fl.on("load", function() {
          fl.maxScale = 0; // show the states layer at all scales
          fl.setSelectionSymbol(new SimpleFillSymbol().setOutline(null).setColor("#AEC7E3"));
        });

        fl.on("click", selectGrid);

        // change cursor to indicate features are click-able
        fl.on("mouse-over", function() {
          map.setMapCursor("pointer");
        });
        fl.on("mouse-out", function() {
          map.setMapCursor("default");
        });

        map.addLayer(fl);

        map.on("load", function(evt) {
          // show the border container now that the dijits
          // are rendered and the map has loaded
          domStyle.set(registry.byId("container").domNode, "visibility", "visible");
          populateGrid(Memory); // pass a reference to the MemoryStore constructor
        });

        function populateGrid(Memory) {
          var qt = new QueryTask(window.statesUrl);
          var query = new Query();
          query.where = "1=1";
          query.returnGeometry = false;
          query.outFields = window.outFields;
          qt.execute(query, function(results) {
            var data = array.map(results.features, function(feature) {
              return {
                // property names used here match those used when creating the dgrid
                "id": feature.attributes[window.outFields[0]],
                "stateName": feature.attributes[window.outFields[1]],
                "median": feature.attributes[window.outFields[2]],
                "over1m": feature.attributes[window.outFields[3]]
              };
            });
            var memStore = new Memory({
              data: data
            });
            window.grid.set("store", memStore);
          });
        }
        // fires when a row in the dgrid is clicked
        function selectState(e) {
          // select the feature
          var queryGrid = new Query();
          queryGrid.objectIds = [parseInt(e.target.innerHTML, 10)];
          fl.selectFeatures(queryGrid, FeatureLayer.SELECTION_NEW, function(result) {
            if (result.length) {
              // re-center the map to the selected feature
              var pt = result[0].geometry.getExtent().getCenter();
              var statePoly = result[0];
              var polyGeom = result[0].geometry;
              map.setExtent(polyGeom.getExtent().expand(2));

              var template = new InfoTemplate({
                title: "Site"
              });
              template.setContent("<tr><b>State Name: </b><td>${NAME}</tr></td><br><tr><b>2012 Median Net Worth (Esri): </b><td>${MEDNW_CY}</tr></td>");

              statePoly.setInfoTemplate(template);
              map.infoWindow.setFeatures([statePoly]);
              map.on('zoom-end', lang.hitch(this, function() {
                map.infoWindow.show(pt);
              }));

            } else {
              alert("Select an OBJECTID to Zoom to Feature");
            };
          });
        }

        // fires when a feature on the map is clicked
        function selectGrid(e) {
          var id = e.graphic.attributes.OBJECTID;
          // select the feature that was clicked
          var query = new Query();
          query.objectIds = [id];
          var states = map.getLayer("states");
          states.selectFeatures(query, FeatureLayer.SELECTION_NEW);
          // select the corresponding row in the grid
          // and make sure it is in view
          grid.clearSelection();
          grid.select(id);
          grid.row(id).element.scrollIntoView();
        }
      });
    });
  </script>
</head>

<body class="tundra">
  <div id="container" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design: 'headline', gutters: false">
    <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'center'"></div>
    <div id="bottomPane" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'bottom'">
      <div id="grid"></div>
    </div>
  </div>
</body>

</html>

View solution in original post

4 Replies
RobertScheitlin__GISP
MVP Emeritus

James,

   Sure here is a sample that takes the find task sample and makes it work with QueryTask instead:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples
      on iOS devices-->
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Query State Info without Map</title>
    <link rel="stylesheet" href="http://js.arcgis.com/3.20/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.20/esri/css/esri.css">

    <style>
    html,
    body{
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
      margin: 0;
      font-family: "Open Sans";
    }
  </style>
    <script src="http://js.arcgis.com/3.20/"></script>
    <script>
      require([
        "esri/graphic", "dojo/_base/array",
        "dojo/dom", "dojo/on",
        "esri/tasks/query", "esri/tasks/QueryTask", "dojo/domReady!"
      ], function (graphic, array, dom, on, Query, QueryTask) {

        var queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/Map...");

        var query = new Query();
        query.returnGeometry = false;
        query.outFields = ["*"];

        on(dom.byId("execute"), "click", execute);

        function execute () {
          query.where = "STATE_NAME Like '%" + dom.byId("searchText").value + "%'";
          queryTask.execute(query, showResults);
        }

        function showResults (results) {
          var resultFeatures = results.features;
          var result, attribs;
          var s = ["<table border=\"1\"><thead><tr style=\"background-color:#ccc;\"><td>State Name</td><td>FIPS</td><td>Population (1990)</td><td>Population (1999)</td></tr></thead><tbody id=\"states\">"];
          array.map(resultFeatures, function(graphic){
            attribs = graphic.attributes;
            s.push("<tr><td>" + attribs.STATE_NAME + "</td><td>" + attribs.STATE_FIPS + "</td><td>" + attribs.POP1990 + "</td><td>" + attribs.POP1999 + "</td></tr>");
          });
          s.push("</tbody></table>");
          dom.byId("tbl").innerHTML = s.join("");
        }
      });
    </script>
  </head>

  <body>
    Find by State Name or State FIPS:
    <input type="text" id="searchText" value="Kansas">
    <input id="execute" type="button" value="Get Details">
    <br />
    <br />
    <div id="tbl"></div>
  </body>
</html>
JamesMitchell4
Deactivated User

Thank you so much. This worked!

My next questions are...
How do i change the styling of the table? Font, heading colour, text size, column width etc...

Howe can i make the row selectable so when it is clicked on the colour changes and i can retrieve the value which i will then use for another query allowing the user to zoom to a feature....

Thank you

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

James,

   Well if you have started with that info I would have given a different sample.

Here is one using dojo dgrid:

Now that you question has been answered twice, be sure to mark this thread as answered and start a new one for further questions.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  <title>Map with a Dojo dGrid</title>

  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dojo/resources/dojo.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dgrid/css/dgrid.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dgrid/css/skins/tundra.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/dijit/themes/tundra/tundra.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.20/esri/css/esri.css">
  <style>
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #container {
      height: 100%;
      visibility: hidden;
    }

    #bottomPane {
      height: 200px;
    }

    #grid {
      height: 100%;
    }

    .dgrid {
      border: none;
    }

    .field-id {
      cursor: pointer;
    }
  </style>

  <script src="http://js.arcgis.com/3.20/"></script>
  <script>
    // load dgrid, esri and dojo modules
    // create the grid and the map
    // then parse the dijit layout dijits
    require([
      "dojo/ready",
      "dgrid/OnDemandGrid",
      "dgrid/Selection",
      "dojo/store/Memory",
      "dojo/_base/array",
      "dojo/dom-style",
      "dijit/registry",
      "esri/map",
      "esri/layers/FeatureLayer",
      "esri/symbols/SimpleFillSymbol",
      "esri/tasks/QueryTask",
      "esri/tasks/query",
      "esri/dijit/PopupTemplate",
      "esri/InfoTemplate",
      "dojo/_base/declare",
      "dojo/number",
      "dojo/on",
      "dojo/_base/lang",
      "dojo/parser",
      "dijit/layout/BorderContainer",
      "dijit/layout/ContentPane"
    ], function(
      ready,
      Grid,
      Selection,
      Memory,
      array,
      domStyle,
      registry,
      Map,
      FeatureLayer,
      SimpleFillSymbol,
      QueryTask,
      Query,
      PopupTemplate,
      InfoTemplate,
      declare,
      dojoNum,
      on,
      lang,
      parser
    ) {
      ready(function() {

        parser.parse();

        // create the dgrid
        window.grid = new(declare([Grid, Selection]))({
          // use Infinity so that all data is available in the grid
          bufferRows: Infinity,
          columns: {
            "id": "ID",
            "stateName": "State Name",
            "median": {
              "label": "Median Net Worth",
              "formatter": dojoNum.format
            },
            "over1m": {
              "label": "Households Net Worth > $1M",
              "formatter": dojoNum.format
            }
          }
        }, "grid");
        // add a click listener on the ID column
        grid.on(".field-id:click", selectState);

        window.map = new Map("map", {
          basemap: "gray",
          center: [-101.426, 42.972],
          zoom: 4
        });

        window.statesUrl = "http://server.arcgisonline.com/ArcGIS/rest/services/Demographics/USA_Median_Net_Worth/MapServer/4";
        window.outFields = ["OBJECTID", "NAME", "MEDNW_CY", "MEDNETWORTH_pct_USAvg"];

        var fl = new FeatureLayer(window.statesUrl, {
          id: "states",
          mode: 1, // ONDEMAND, could also use FeatureLayer.MODE_ONDEMAND
          outFields: window.outFields
        });

        fl.on("load", function() {
          fl.maxScale = 0; // show the states layer at all scales
          fl.setSelectionSymbol(new SimpleFillSymbol().setOutline(null).setColor("#AEC7E3"));
        });

        fl.on("click", selectGrid);

        // change cursor to indicate features are click-able
        fl.on("mouse-over", function() {
          map.setMapCursor("pointer");
        });
        fl.on("mouse-out", function() {
          map.setMapCursor("default");
        });

        map.addLayer(fl);

        map.on("load", function(evt) {
          // show the border container now that the dijits
          // are rendered and the map has loaded
          domStyle.set(registry.byId("container").domNode, "visibility", "visible");
          populateGrid(Memory); // pass a reference to the MemoryStore constructor
        });

        function populateGrid(Memory) {
          var qt = new QueryTask(window.statesUrl);
          var query = new Query();
          query.where = "1=1";
          query.returnGeometry = false;
          query.outFields = window.outFields;
          qt.execute(query, function(results) {
            var data = array.map(results.features, function(feature) {
              return {
                // property names used here match those used when creating the dgrid
                "id": feature.attributes[window.outFields[0]],
                "stateName": feature.attributes[window.outFields[1]],
                "median": feature.attributes[window.outFields[2]],
                "over1m": feature.attributes[window.outFields[3]]
              };
            });
            var memStore = new Memory({
              data: data
            });
            window.grid.set("store", memStore);
          });
        }
        // fires when a row in the dgrid is clicked
        function selectState(e) {
          // select the feature
          var queryGrid = new Query();
          queryGrid.objectIds = [parseInt(e.target.innerHTML, 10)];
          fl.selectFeatures(queryGrid, FeatureLayer.SELECTION_NEW, function(result) {
            if (result.length) {
              // re-center the map to the selected feature
              var pt = result[0].geometry.getExtent().getCenter();
              var statePoly = result[0];
              var polyGeom = result[0].geometry;
              map.setExtent(polyGeom.getExtent().expand(2));

              var template = new InfoTemplate({
                title: "Site"
              });
              template.setContent("<tr><b>State Name: </b><td>${NAME}</tr></td><br><tr><b>2012 Median Net Worth (Esri): </b><td>${MEDNW_CY}</tr></td>");

              statePoly.setInfoTemplate(template);
              map.infoWindow.setFeatures([statePoly]);
              map.on('zoom-end', lang.hitch(this, function() {
                map.infoWindow.show(pt);
              }));

            } else {
              alert("Select an OBJECTID to Zoom to Feature");
            };
          });
        }

        // fires when a feature on the map is clicked
        function selectGrid(e) {
          var id = e.graphic.attributes.OBJECTID;
          // select the feature that was clicked
          var query = new Query();
          query.objectIds = [id];
          var states = map.getLayer("states");
          states.selectFeatures(query, FeatureLayer.SELECTION_NEW);
          // select the corresponding row in the grid
          // and make sure it is in view
          grid.clearSelection();
          grid.select(id);
          grid.row(id).element.scrollIntoView();
        }
      });
    });
  </script>
</head>

<body class="tundra">
  <div id="container" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design: 'headline', gutters: false">
    <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'center'"></div>
    <div id="bottomPane" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'bottom'">
      <div id="grid"></div>
    </div>
  </div>
</body>

</html>
JamesMitchell4
Deactivated User

Thank you very much for your help

0 Kudos