Select to view content in your preferred language

How to add QueryTask result to map as a new Layer

2024
5
Jump to solution
07-25-2018 05:06 PM
MarkJones7
Regular Contributor

ok, i have given this the old college try but have reached a road block that I cannot seem to get past.

I have written the following code (added below as well as attached to this post) and am able to properly execute the QueryTask (as per the console output), but what I haven't been able to figure out is how to take the results, create a new layer from those results, and then add that layer to the map (i.e. a layer showing each point as a pin on the map). Any guidance, help, etc. is immensely appreciated.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>API Demo for Crime App API</title>
  <link rel="stylesheet" href="https://js.arcgis.com/4.8/esri/css/main.css">
<script src="https://js.arcgis.com/4.8/"></script>  
<style>
html,
body,
#viewDiv {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
</style>
</head>
 <body>
  <div id="viewDiv"></div>
<script>
require([
  "esri/Map",
  "esri/views/MapView",
  "esri/layers/FeatureLayer", 
  "esri/tasks/QueryTask", 
  "esri/tasks/support/Query",
  "dojo/on",
  "dojo/dom",
  "dojo/domReady!"
], function(
  Map,
  MapView,
   FeatureLayer,
  QueryTask,
  Query,
   Popup,
   Search,
  on,
  dom
) { //TOP of REQUIRE
  // Code starts here
 var ftLayer = new FeatureLayer(
  {
    url: "https://services.arcgis.com/S9th0jAJ7bqgIRjw/ArcGIS/rest/services/YTD_Crime/FeatureServer/0",
    outFields: ["*"],
    definitionExpression:"mci_category = 'Shooting'" 
  });
  
var qryLayerUrl = "https://services.arcgis.com/S9th0jAJ7bqgIRjw/ArcGIS/rest/services/YTD_Crime/FeatureServer/0";

 var queryTask = new QueryTask({
    url: qryLayerUrl
  });


var query = new Query();
  query.returnGeometry = true;
  query.outFields = ["*"];
  query.where = "mci_category = 'Shooting'";  
  queryTask.execute(query).then(function(results){
    console.log(results.features);
  });


queryTask.executeForCount(query).then(function(results){
    console.log(results);
  });

  // Create the map
  var map = new Map({
    basemap: "streets"
    
  });

  // Create the view
  var view = new MapView({
    container: "viewDiv",
    map: map,
    zoom: 10,
    center: [-79.3832, 43.6532]
  });

});

</script>
  </body> 
</html>

Thanks,

Mark

0 Kudos
1 Solution

Accepted Solutions
UndralBatsukh
Esri Regular Contributor

Hi there, 

Results are not displayed in the view because the spatialReference of your FeatureService does not match the spatialReference of the view. So you need to set the outSpatialReference of the query to match the view's spatialReference as shown below. 

query.where = "mci_category = 'Shooting'"; 
query.outSpatialReference = view.spatialReference;

Here your application updated and the results are displayed. 

View solution in original post

5 Replies
JohnGrayson
Esri Regular Contributor
0 Kudos
MarkJones7
Regular Contributor

Thanks for the response John. I took a look at that url and was able to reduce it to the main parts that I need, but I still find myself not being able to add the results to the map. Here is my version of the code from the url you provided:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
  <title>Query features from a FeatureLayer - 4.8</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.8/esri/css/main.css">
  <script src="https://js.arcgis.com/4.8/"></script>

  <style>
    html,
    body,
    #viewDiv {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }

    #infoDiv {
      background-color: white;
      color: black;
      padding: 6px;
      width: 400px;
    }

    #results {
      font-weight: bolder;
    }
  </style>

  <script>
    require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/FeatureLayer",
        "esri/layers/GraphicsLayer",
        "esri/geometry/geometryEngine",
        "esri/Graphic",

        "dojo/on",
        "dojo/dom",
        "dojo/dom-construct",
        "dojo/domReady!"
      ],
      function(
        Map, MapView,
        FeatureLayer,
        GraphicsLayer,
        geometryEngine,
        Graphic,
        on, dom, domConstruct
      ) {

        var occsUrl =
          "https://services.arcgis.com/S9th0jAJ7bqgIRjw/ArcGIS/rest/services/YTD_Crime/FeatureServer/0";


        var queryOccs = dom.byId("query-occs");

 

        // occurrences
        var occsLayer = new FeatureLayer({
          url: occsUrl,
          outFields: ["*"],
          visible: false
        });

        // GraphicsLayer for displaying results
        var resultsLayer = new GraphicsLayer();

        var map = new Map({
          basemap: "dark-gray",
          //layers: [wellsLayer, quakesLayer, resultsLayer]
          layers: [resultsLayer]
        });

        var view = new MapView({
          container: "viewDiv",
          map: map,
    zoom: 10,
    center: [-79.3832, 43.6532]
        });
        view.ui.add("infoDiv", "top-right");




       on(queryOccs, "click", function() {
          queryOccurrences()
            .then(displayResults);
        });

        function queryOccurrences() {
          var query = occsLayer.createQuery();
        //   query.returnGeometry = true;
  //query.outFields = ["*"];
         query.where = "mci_category = 'Shooting'"; 
         // query.geometry = wellBuffer;
        //  query.spatialRelationship = "intersects";

          return occsLayer.queryFeatures(query);
        }

        // display the query results in the
        // view and print the number of results to the DOM
        function displayResults(results) {

          resultsLayer.removeAll();
          var features = results.features.map(function(graphic) {
            graphic.symbol = {
              type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
              style: "diamond",
              size: 6.5,
              color: "darkorange"
            };
            return graphic;
          });
          var numOccs = features.length;
          dom.byId("results").innerHTML = numOccs + " occurrences found";
          resultsLayer.addMany(features);
        }

      });
  </script>

</head>

<body>
  <div id="viewDiv"></div>
  <div id="infoDiv">
    
    <button id="query-occs">Query Occurrences</button>
    <br>
    <div id="results"></div>
  </div>
</body>

</html>

Any further insight is greatly appreciated. I will try and add the above code as a file to the original post

0 Kudos
JohnGrayson
Esri Regular Contributor

Do you have a codepen (or something similar) so we can actually see what might be going on?

0 Kudos
UndralBatsukh
Esri Regular Contributor

Hi there, 

Results are not displayed in the view because the spatialReference of your FeatureService does not match the spatialReference of the view. So you need to set the outSpatialReference of the query to match the view's spatialReference as shown below. 

query.where = "mci_category = 'Shooting'"; 
query.outSpatialReference = view.spatialReference;

Here your application updated and the results are displayed. 

MarkJones7
Regular Contributor

You Sir are a genius! Thank you very much!

0 Kudos