Class Breaks Renderer on Graphics

401
10
Jump to solution
3 weeks ago
jaykapalczynski
Frequent Contributor

How do I create a Class Breaks Renderer on a Graphic...

I am following this https://community.esri.com/t5/python-questions/create-definition-query/m-p/1060578/thread-id/61196#M...

But it does the below....... but I want a class breaks renderer

 

function addGraphics(result) {
  graphicsLayer.removeAll();
  result.features.forEach(function (feature) {
    var g = new Graphic({
      geometry: feature.geometry,
      attributes: feature.attributes,
      symbol: {
        type: "simple-marker",
        color: [0, 0, 0],
        outline: {
          width: 2,
          color: [0, 255, 255]
        },
        size: "20px"
      },

 

Can I do something like this?

      var less1 = new SimpleFillSymbol({
        color: "gray",
        style: "none",
        outline: {
          width: 0,
          color: "white"
        }
      });
      var more1 = new SimpleFillSymbol({
        color: "green",
        style: "solid",
        outline: {
          width: 0.5,
          color: "white"
        }
      });
      var more100 = new SimpleFillSymbol({
        color: "Blue",
        style: "solid",
        outline: {
          width: 0.5,
          color: "white"
        }
      });

	  
      var renderer = new ClassBreaksRenderer({
        field: "SomeField",
        defaultSymbol: new SimpleFillSymbol({
          color: "red",
          outline: {
            width: 0.5,
            color: "white"
          }
        }),
        defaultLabel: "no data",
        classBreakInfos: [
        {
          minValue: 0,
          maxValue: 0.9,
          symbol: less1,
          label: "< 1"
        }, {
          minValue: 1.01,
          maxValue: 50.0,
          symbol: more1,
          label: "1 - 50"
        }, {
          minValue: 50.01,
          maxValue: 100.00,
          symbol: more100,
          label: "> 50"
        }]
      });

function addGraphics(result) {
  graphicsLayer.removeAll();
  result.features.forEach(function (feature) {
    var g = new Graphic({
      geometry: feature.geometry,
      attributes: feature.attributes,
      renderer : renderer
0 Kudos
1 Solution

Accepted Solutions
jaykapalczynski
Frequent Contributor

Solved with the help of ESRI Services...

Set the Source on the New Feature layer to that of graphicsLayer.graphics

I then make sure that I add that New Feature Layer after the code is run to populate the graphics layer.

 

 

 

 

<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 | Sample | ArcGIS API for JavaScript 4.19</title>

<script>
  var dojoConfig = {
    has: {
      "esri-featurelayer-webgl": 1
    }
  };
</script>

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

<style>
#container {
  width: 100%;
  height: 100%;
  position: relative;
}

#viewDiv {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
        #infoDiv {
          background-color: white;
          color: black;
          padding: 6px;
          width: 400px;
        }

        #results {
          font-weight: bolder;
          padding-top: 10px;
        }
        #drop-downs{
          padding-bottom: 15px;
        }

      </style>

      <script>
        require([
          "esri/Map",
          "esri/views/MapView",
          "esri/layers/FeatureLayer",
          "esri/layers/GraphicsLayer",
          "esri/geometry/geometryEngine",
          "esri/Graphic",
          "esri/widgets/Slider",
		  "esri/symbols/SimpleFillSymbol",
		  "esri/PopupTemplate",
		  "esri/renderers/ClassBreaksRenderer",
		  "esri/renderers/SimpleRenderer"
        ], function(Map, MapView, FeatureLayer, GraphicsLayer, 
	   geometryEngine, Graphic, Slider, 
	   SimpleFillSymbol, PopupTemplate, ClassBreaksRenderer, SimpleRenderer) 
		{
		
          var wellBuffer, wellsGeometries, magnitude;
          var wellTypeSelect = document.getElementById("well-type");
		
          var pointsUrl ="https://xxxx/arcgis/rest/services/Test/Test/FeatureServer/0";
          // historic earthquakes
          var pointsLayer = new FeatureLayer({
            url: pointsUrl,
            outFields: ["*"],
			minScale: 400000,
            visible: false,
            popupTemplate: template
          });
		

          var polygonUrl ="https://xxxx/arcgis/rest/services/Test/Test/FeatureServer/1";
          var polygonLayer = new FeatureLayer({
            url: polygonUrl,
            outFields: ["*"],
            visible: false
          });


          // GraphicsLayer for displaying results
          var resultsPolygonLayer2 = new GraphicsLayer({		  
		  });		  

      var less1 = new SimpleFillSymbol({
        color: "gray",
        style: "none",
		opacity: .5,
        outline: {
          width: 0.1,
          color: "gray"
        }
      });
      var moreseventy = new SimpleFillSymbol({
        color: "Blue",
        style: "solid",
		opacity: .5,
        outline: {
          width: 0.1,
          color: "gray"
        }
      });

	  
	  var fieldChoosen = "";
	  fieldChoosen = "Field 1";
	  
      var rendererPolygon = new ClassBreaksRenderer({
        field: fieldChoosen,
        //normalizationField: "EDUCBASECY",
        defaultSymbol: new SimpleFillSymbol({
          color: "red",
          outline: {
            width: 0.5,
            color: "white"
          }
        }),
        defaultLabel: "no data",
        classBreakInfos: [
        {
          minValue: 0,
          maxValue: 0.9,
          symbol: less1,
          label: "< 1"
        },{
          minValue: 70.01,
          maxValue: 200.00,
          symbol: moreseventy,
          label: "> 70"
        }]
      });

        // create empty FeatureLayer
        const monumentLayer = new FeatureLayer({
          // create an instance of esri/layers/support/Field for each field object
          title: "",
          fields: [
            {
              name: "OBJECTID",
              alias: "ObjectID",
              type: "oid"
            },
            {
              name: "Field1",
              alias: "Field 1",
              type: "string"
            }
          ],
          objectIdField: "OBJECTID",
          geometryType: "polygon",
          spatialReference: { wkid: 3857 },
          source: resultsPolygonLayer2.graphics,
          renderer: rendererPolygon,
          popupTemplate: {
            title: "{OBJECTID}"
          }
        });
		
          // SET THE MIN MAX SCALE TO TURN GRAPHICS LAYERS ON AND OFF BASED ON ZOOM
	      resultsPolygonLayer2.minScale = 400000;

     	  var map = new Map({
            basemap: "dark-gray-vector",
            layers: [pointsLayer, polygonLayer,  resultsPolygonLayer2]
          });

          var view = new MapView({
            container: "viewDiv",
            map: map,
		    center: [-78.989586, 37.566286],
		    zoom: 6
          });
          view.ui.add("infoDiv", "top-right");
		  
          // query all features from the points layer
          view
            .when(function() {
              return pointsLayer.when(function() {
                var query = pointsLayer.createQuery();
                return pointsLayer.queryFeatures(query);
              });
            })
            .then(getValues)
            .then(getUniqueValues)
            .then(addToSelect)
            .then(createBuffer);		  

          function getValues(response) {
            var features = response.features;
            var values = features.map(function(feature) {
              return feature.attributes.common_name;
            });
            return values;
          }
          // return an array of unique values in
          // the STATUS2 field of the wells layer
          function getUniqueValues(values) {
            var uniqueValues = [];
            uniqueValues.push("A Select Species");
            values.forEach(function(item, i) {
              if ((uniqueValues.length < 1 || uniqueValues.indexOf(item) === -1) && item !== "") {
                uniqueValues.push(item);
              }
            });
			uniqueValues.sort();
			return uniqueValues;
          }

          function addToSelect(values) {
            values.sort();
            values.forEach(function(value) {
              var option = document.createElement("option");
              option.text = value;
              wellTypeSelect.add(option);
            });
	    return setWellsDefinitionExpression(wellTypeSelect.value);
          }

          // set the definition expression on the wells
          // layer to reflect the selection of the user
          function setWellsDefinitionExpression(newValue) {
            pointsLayer.definitionExpression = "common_name = '" + newValue + "'";
            if (!pointsLayer.visible) {
              pointsLayer.visible = true;
            }
            return queryForWellGeometries();
          }

          // Get all the geometries of the wells layer
          // the createQuery() method creates a query
          // object that respects the definitionExpression
          // of the layer
          function queryForWellGeometries() {
            var pointsQuery = pointsLayer.createQuery();
            return pointsLayer.queryFeatures(pointsQuery).then(function(response) {
              pointsGeometries = response.features.map(function(feature) {
                return feature.geometry;
              });
              return pointsGeometries;
            });			        		
          }

          var bufferGraphic = null;
          function createBuffer(wellPoints) {
		  		
            //var bufferDistance = distanceSlider.values[0];
            var bufferDistance = 1;
			var wellBuffers = geometryEngine.geodesicBuffer(wellPoints, [bufferDistance], "meters", true);
            wellBuffer = wellBuffers[0];

		queryPolygons2().then(displayResults2);
		zoompolygons();
          }

		  function zoompolygons(){
			// ZOOM TO THE RETURNED FEATURES
			let opts = {
               duration: 5000  // Duration of animation will be 5 seconds
            };

		    pointsLayer.queryExtent().then((response) => {
				// go to the extent of all the graphics in the layer view
				view.goTo({
					target: (response.extent.clone().expand(1.0112))
				}, opts);
		    });
				
		monumentLayer.refresh();
          }


          // set a new definitionExpression on the wells layer
          // and create a new buffer around the new wells
          wellTypeSelect.addEventListener("change", function() {
            var type = event.target.value;
            setWellsDefinitionExpression(type).then(createBuffer);

map.remove(monumentLayer);

          });



          function queryPolygons2() {
            var query = polygonLayer.createQuery();
            query.geometry = wellBuffer;
            query.spatialRelationship = "intersects";
		
            return polygonLayer.queryFeatures(query);
          }
		  
          // display the earthquake query results in the
          // view and print the number of results to the DOM

 
	function displayResults2(results) {
            resultsPolygonLayer2.removeAll();
	
            var features = results.features.map(function(graphic) {
              graphic.symbol = {
                type: "simple-fill", // autocasts as new SimpleMarkerSymbol()
				style: "none",
				outline: {  // autocasts as new SimpleLineSymbol()
				  color: "gray",
				  width: 1
				},
				opacity: .5,
                color: [ 51,51, 204, 0.9 ]
              };

              return graphic;

            });

            var numPolygons = features.length;
            document.getElementById("results").innerHTML = numPolygons + " grids found";

		resultsPolygonLayer2.addMany(features);

// SET THE SOURCE OF THE GRAPHICS LAYER TO THE MONUMENT LAYER			
monumentLayer.source = resultsPolygonLayer2.graphics;
map.remove(monumentLayer);
// ADD THE MONUMNET LAYER TO THE MAP
map.add(monumentLayer);
		  }


		
        }); // END OF MAIN FUNCTION
      </script>
    </head>

    <body>
	<div id="container">
      <div id="viewDiv"></div>
    	<div id="infoDiv" class="esri-widget">
			<div id="drop-downs">
			  Select Species type:
			  <select id="well-type" class="esri-widget"></select>
			</div>
			<div id="results" class="esri-widget"></div>
		  </div>

	</div>
    </body>
  </html>

 

 

 

View solution in original post

0 Kudos
10 Replies
jaykapalczynski
Frequent Contributor
  1. I have a polygon FC and Point FC
  2. I start by doing a query on the point FC
  3. I then create a buffer around those points
  4. I then call two functions to query the Polygons that intersect this buffer and then to add the graphics to a graphics layer.
  5.  

but I want to use a class breaks renderer....do I need to create a new Feature Layer instead of graphics layer to use the class breaks renderer....

If so how do I write the results of the query to the new feature layer?

 

          var polygonUrl ="https://xxxxarcgis/rest/services/Test/FeatureServer/1";
          var polygonLayer = new FeatureLayer({
            url: polygonUrl,
            outFields: ["*"],
            visible: false
          });

// THIS IS THE NEW POLYGON GRPAHICS LAYER TO HOLE RESULTS OF QUERY
var graphicsLayerNew = new GraphicsLayer({
 opacity: .5,
});

          view
            .when(function() {
              return pointsLayer.when(function() {
                var query = pointsLayer.createQuery();
                return pointsLayer.queryFeatures(query);
              });
            })
            .then(createBuffer);

          function createBuffer(wellPoints) {
            var bufferDistance = 200;
	    var wellBuffers = geometryEngine.geodesicBuffer(wellPoints, [bufferDistance], "meters", true);
            wellBuffer = wellBuffers[0];

            queryPolygonsNew().then(addGraphics);
          }

function queryPolygonsNew() {
    var query = polygonLayer.createQuery();
    query.geometry = wellBuffer;
    query.outfields = ["*"];
    query.spatialRelationship = "intersects";

    return polygonLayer.queryFeatures(query);
}
function addGraphics(results) {
  graphicsLayerNew.removeAll();
  results.features.forEach(function  (feature) {
    var g = new Graphic({
      geometry: feature.geometry,
      attributes: feature.attributes,
	symbol: {
        type: "simple-fill", // autocasts as new SimpleMarkerSymbol()
        style: "solid",
	outline: {  // autocasts as new SimpleLineSymbol()
	color: "white",
	width: 1
	},
	opacity: .5,
        color: [ 51,51, 204, 0.9 ]
      },
      popupTemplate: {
        title: "Quad Name {QUAD_NAME}",
        content: "The Objectid = {OBJECTID} points located in {QUAD} Quad."
      }
    });
    graphicsLayerNew.add(g);
  });
}

 

0 Kudos
jaykapalczynski
Frequent Contributor

It appears that I need a Feature Layer, as it does not appear a graphics layer can use a Class Breaks Renderer.

So I guess my question is now:

  1. How do I return the results from a query to a new Feature Layer that I can use a renderer on?
  2. I then need to clear and update the Feature Layer every time the query is run.

Does any one know how to do this....Write results of a query to a new Feature Layer rather than a Graphic?

 

jaykapalczynski_0-1621953082801.png

 

 

0 Kudos
jaykapalczynski
Frequent Contributor

Ok thanks this is making a bit more sense now.....maybe you can shed some light on this part....

  1. Ok i am in the Function createBuffer() that then creates a buffered geometry of a bunch of points.
  2. This then calls the queryPolygons() function that queries the polygon Feature Layer to return the polygons that intersect with the Points (wellbuffer geometry)
  3. My problem is when I then call the addFeatures query using the .then inside createBuffer()
  4. I am passing Polygons and the example uses points:  I am trying to capture all the polygons from the query in the addFeatures() function with this: 
  5.          var returnedPolygons = results.features.map(function(graphic) {});
  6. And then in the same function I need to figure out how to properly define a polygon and not a point

So I am stuck on how to take the retuned polygons, write them to array and then properly add them to the graphics array

ANY thoughts?

I want to use the returnedPolygons variable instead of the data array but this is a polygon and does not have Lat and Long fields like the point example

 

 

            for (var i=0; i<data.length; i++){
                graphic = new Graphic({
                    geometry: {
                        type: "point",
                        latitude: data[i].LATITUDE,
                        longitude: data[i].LONGITUDE
                    },
                    attributes: data[i]
                });
                graphics.push(graphic);
            }

 

 

 

 

 

         var bufferGraphic = null;
          function createBuffer(wellPoints) {
            var bufferDistance = 1
			var wellBuffers = geometryEngine.geodesicBuffer(wellPoints, [bufferDistance], "meters", true);
            wellBuffer = wellBuffers[0];

			queryPolygons().then(addFeatures);			
          }

          function queryPolygons() {
            var query = polygonLayer.createQuery();
            //query.where = "mag >= " + magSlider.values[0];
            query.geometry = wellBuffer;
            query.spatialRelationship = "intersects";

            return polygonLayer.queryFeatures(query);
          }

        function addFeatures(results){
            // data to be added to the map
			
		    var returnedPolygons = results.features.map(function(graphic) {
            });
			
        
			const data = [
                {
                    LATITUDE: 32.6735,
                    LONGITUDE: -83.2425,
                    TYPE: "National Monument",
                    NAME: "Cabrillo National Monument"
                },
                {
                    LATITUDE: 34.2234,
                    LONGITUDE: -79.5590,
                    TYPE: "National Monument",
                    NAME: "Cesar E. Chavez National Monument"
                },
                {
                    LATITUDE: 37.6251,
                    LONGITUDE: -82.0850,
                    TYPE: "National Monument",
                    NAME: "Devils Postpile National Monument"
                }
            ];
        
            // create an array of graphics based on the data above
            var graphics = [];
            var graphic;
            for (var i=0; i<returnedPolygons.length; i++){
                graphic = new Graphic({
                    geometry: {
                        type: "point",
                        latitude: data[i].LATITUDE,
                        longitude: data[i].LONGITUDE
                    },
                    attributes: data[i]
                });
                graphics.push(graphic);
            }
            // addEdits object tells applyEdits that you want to add the features
            const addEdits = {
                addFeatures: graphics
            };
            // apply the edits to the layer
            applyEditsToLayer(addEdits);
        }

 

 

 

 

0 Kudos
ReneRubalcava
Frequent Contributor

This might help, it shows how to copy the schema of a FeatureLayer and copy features to the new layer that you can apply a new renderer to.

https://codepen.io/odoe/pen/QWGRJNg

0 Kudos
jaykapalczynski
Frequent Contributor

I know I am getting a return from the Polygon query as I can alert the object:

function addFeatures(results){			
     var returnedPolygons = results;
     alert(JSON.stringify(returnedPolygons));

 

jaykapalczynski_0-1621956920409.png

 

0 Kudos
jaykapalczynski
Frequent Contributor

I think something is wrong here....

I alert the correct number of polygons from the Rowcount varaible

but when I alert the addEdits I get nothing in the array but the schema.

jaykapalczynski_0-1621962879377.png

 

            // create an array of graphics based on the data above
            var graphics = [];
            var graphic;
			var rowcount = 0;
            for (var i=0; i < returnedPolygons.length; i++){
                graphic = new Graphic({
                    geometry: {
                        type: "polygon"
                    },
                    attributes: returnedPolygons[i]
                });
                graphics.push(graphic);
				rowcount = rowcount + 1;
            }
			
	alert ("Rowcount: " + rowcount);
            // addEdits object tells applyEdits that you want to add the features
            const addEdits = {
                addFeatures: graphics
            };

			alert ("add edits: " + (JSON.stringify(addEdits)));

 

 

0 Kudos
JohnGrayson
Esri Regular Contributor

You would need to use a FeatureLayer with client-side graphics, and you'd have to use applyEdits() to manage the data being added/removed to/from the layer.

0 Kudos
jaykapalczynski
Frequent Contributor

I know I am close....if you have a second....I am getting returned results for the polygon search...it says they are added to the Feature Layer in the console but nothing is showing up....

I am at a loss here....hopefully someone can point out my mistake....why are the returned polygons not showing up in the map

Simply select a species in the drop down and give a couple seconds to draw

In the last alert I am only seeing schema and not values to update....which is why I think there is nothing rendering

If you select a species from the drop down select "Dunlin" as there are only 26 of them and wont only get in the loop 26 times.

Maybe a projection issues...the Feature Layer data is UTM zone 17, map I tried to make the same

 

UPDATED WTITH NEW CODE....

 

 

 

 

<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 | Sample | ArcGIS API for JavaScript 4.19</title>

<script>
  var dojoConfig = {
    has: {
      "esri-featurelayer-webgl": 1
    }
  };
</script>

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

<style>
#container {
  width: 100%;
  height: 100%;
  position: relative;
}

#viewDiv {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

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

        #results {
          font-weight: bolder;
          padding-top: 10px;
        }
        .slider{
          width: 100%;
          height: 60px;
        }
        #drop-downs{
          padding-bottom: 15px;
        }
		.loader {
		  border: 16px solid #f3f3f3; /* Light grey */
		  border-top: 16px solid #3498db; /* Blue */
		  border-radius: 50%;
		  width: 20px;
		  height: 20px;
		  animation: spin 2s linear infinite;
		}

		@keyframes spin {
		  0% { transform: rotate(0deg); }
		  100% { transform: rotate(360deg); }
		}

      </style>

      <script>
        require([
          "esri/Map",
          "esri/views/MapView",
          "esri/layers/FeatureLayer",
          "esri/layers/GraphicsLayer",
          "esri/geometry/geometryEngine",
          "esri/Graphic",
          "esri/widgets/Slider",
		  "esri/symbols/SimpleFillSymbol",
		  "esri/PopupTemplate",
		  "esri/renderers/ClassBreaksRenderer",
		  "esri/renderers/SimpleRenderer"
        ], function(Map, MapView, FeatureLayer, GraphicsLayer, 
		            geometryEngine, Graphic, Slider, 
					SimpleFillSymbol, PopupTemplate, ClassBreaksRenderer, SimpleRenderer) 
		{


		// HERE IS THE EXAMPLE
		// https://developers.arcgis.com/javascript/latest/sample-code/sandbox/index.html?sample=featurelayer-query
		
          var wellBuffer, wellsGeometries, magnitude;

          var wellTypeSelect = document.getElementById("well-type");


      var less1 = new SimpleFillSymbol({
        color: "gray",
        style: "none",
        outline: {
          width: 0,
          color: "white"
        }
      });
      var less10 = new SimpleFillSymbol({
        color: "green",
        style: "solid",
        outline: {
          width: 0.5,
          color: "white"
        }
      });
      var less30 = new SimpleFillSymbol({
        color: "orange",
        style: "solid",
        outline: {
          width: 0.5,
          color: "white"
        }
      });
      var more30 = new SimpleFillSymbol({
        color: "red",
        style: "solid",
        outline: {
          width: 0.5,
          color: "white"
        }
      });
      var more100 = new SimpleFillSymbol({
        color: "Blue",
        style: "solid",
        outline: {
          width: 0.5,
          color: "white"
        }
      });

	  
      var rendererPolygon = new ClassBreaksRenderer({
        field: "AcadianFlycatcher",
        //normalizationField: "EDUCBASECY",
        defaultSymbol: new SimpleFillSymbol({
          color: "red",
          outline: {
            width: 0.5,
            color: "white"
          }
        }),
        defaultLabel: "no data",
        classBreakInfos: [
        {
          minValue: 0,
          maxValue: 0.9,
          symbol: less1,
          label: "< 1"
        }, {        
          minValue: 0,
          maxValue: 10.0,
          symbol: less10,
          label: "< 10"
        }, {
          minValue: 10.01,
          maxValue: 30.00,
          symbol: less30,
          label: "10 - 30"
        }, {
          minValue: 30.01,
          maxValue: 50.0,
          symbol: more30,
          label: "30 - 50%"
        }, {
          minValue: 50.01,
          maxValue: 100.00,
          symbol: more100,
          label: "> 100"
        }]
      });

		//Spatial Reference: 102100  (3857)
		// wkid: 4326
          var pointsUrl ="https://xxxxxxx/arcgis/rest/services/Test/Polygon_Test/FeatureServer/0";
          // historic earthquakes
          var pointsLayer = new FeatureLayer({
            url: pointsUrl,
			spatialReference: { wkid: 3857 },
            outFields: ["*"],
			//minScale: 400000,
            visible: false
          });
		

          var polygonUrl ="https://xxxxxxx/arcgis/rest/services/Test/Polygon_Test/FeatureServer/1";
          // historic earthquakes
          var polygonLayer = new FeatureLayer({
            url: polygonUrl,
			spatialReference: { wkid: 3857 },
            outFields: ["*"],
            visible: false
          });
		  
let rendererNew = {
  type: "simple",  // autocasts as new SimpleRenderer()
  symbol: {
    type: "simple-fill",  // autocasts as new SimpleFillSymbol()
    color: [ 255, 128, 0, 0.5 ],
    outline: {  // autocasts as new SimpleLineSymbol()
      width: 1,
      color: "white"
    }
  }
};
		  
        // create empty FeatureLayer
        const monumentLayer = new FeatureLayer({
          // create an instance of esri/layers/support/Field for each field object
          title: "National Monuments",
          fields: [
            {
              name: "OBJECTID",
              alias: "ObjectID",
              type: "oid"
            },
            {
              name: "AcadianFlycatcher",
              alias: "AcadianFlycatcher",
              type: "string"
            }
          ],
          objectIdField: "OBJECTID",
          geometryType: "polygon",
          spatialReference: { wkid: 3857 },
          source: [], // adding an empty feature collection
          renderer: rendererNew,
          popupTemplate: {
            title: "{Name}"
          }
        });


     	  var map = new Map({
            basemap: "dark-gray-vector",
            layers: [pointsLayer, polygonLayer, monumentLayer]
          });

          var view = new MapView({
            container: "viewDiv",
            map: map,
		    center: [-78.989586, 37.566286],
		    zoom: 6,
			spatialReference: {
			  wkid: 3857
			}
          });
          view.ui.add("infoDiv", "top-right");

const removeBtn = document.getElementById("remove");
removeBtn.addEventListener("click", removeFeatures);


          // query all features from the points layer
          view
            .when(function() {
              return pointsLayer.when(function() {
                var query = pointsLayer.createQuery();
                return pointsLayer.queryFeatures(query);
              });
            })
            .then(getValues)
            .then(getUniqueValues)
            .then(addToSelect)
            .then(createBuffer);

          // return an array of all the values in the
          // STATUS2 field of the wells layer
          function getValues(response) {
            var features = response.features;
            var values = features.map(function(feature) {
              return feature.attributes.common_name;
            });
            return values;
          }
          // return an array of unique values in
          // the STATUS2 field of the wells layer
          function getUniqueValues(values) {
            var uniqueValues = [];
            uniqueValues.push("A Select Species");
            values.forEach(function(item, i) {
              if ((uniqueValues.length < 1 || uniqueValues.indexOf(item) === -1) && item !== "") {
                uniqueValues.push(item);
              }
            });
			uniqueValues.sort();
			return uniqueValues;
          }

          // Add the unique values to the wells type
          // select element. This will allow the user
          // to filter wells by type.
          function addToSelect(values) {
            values.sort();
            values.forEach(function(value) {
              var option = document.createElement("option");
              option.text = value;
              wellTypeSelect.add(option);
            });		
			
            return setWellsDefinitionExpression(wellTypeSelect.value);
          }

          // set the definition expression on the wells
          // layer to reflect the selection of the user
          function setWellsDefinitionExpression(newValue) {
            pointsLayer.definitionExpression = "common_name = '" + newValue + "'";
            if (!pointsLayer.visible) {
              pointsLayer.visible = true;
            }
            return queryForWellGeometries();
          }

          // Get all the geometries of the wells layer
          // the createQuery() method creates a query
          // object that respects the definitionExpression
          // of the layer
          function queryForWellGeometries() {
            var pointsQuery = pointsLayer.createQuery();
            return pointsLayer.queryFeatures(pointsQuery).then(function(response) {
              pointsGeometries = response.features.map(function(feature) {
                return feature.geometry;
              });
              return pointsGeometries;
            });			        		
          }

          var bufferGraphic = null;
          function createBuffer(wellPoints) {
            var bufferDistance = 1
			var wellBuffers = geometryEngine.geodesicBuffer(wellPoints, [bufferDistance], "meters", true);
            wellBuffer = wellBuffers[0];

			queryPolygons().then(addFeatures);			
          }


		  function zoompolygons(){
			// ZOOM TO THE RETURNED FEATURES
			let opts = {
               duration: 5000  // Duration of animation will be 5 seconds
            };
		    pointsLayer.queryExtent().then((response) => {
				// go to the extent of all the graphics in the layer view
				view.goTo({
					target: (response.extent.clone().expand(1.0112))
				}, opts);
		    });	
          }



          // set a new definitionExpression on the wells layer
          // and create a new buffer around the new wells
          wellTypeSelect.addEventListener("change", function() {
            var type = event.target.value;
            setWellsDefinitionExpression(type).then(createBuffer);
          });

          function queryPolygons() {
            var query = polygonLayer.createQuery();
            //query.where = "mag >= " + magSlider.values[0];
            query.geometry = wellBuffer;
            query.spatialRelationship = "intersects";

            return polygonLayer.queryFeatures(query);
          }

        // fires when "Add Features" button is clicked
        function addFeatures(results){
            // data to be added to the map

			var returnedPolygons = results;
			
		    //var returnedPolygons = results.features.map(function(graphic){});
			var returnedPolygons2 = results.features;
			
			//alert(JSON.stringify(returnedPolygons));
			var data = (JSON.stringify(returnedPolygons2));
 
			alert ("Returned Polygons Results Length: " + returnedPolygons2.length);
			alert ("Returned JSON stringify Results: " + data);			
			alert ("Returned JSON stringify Count: " + data.length);
			//alert (returnedPolygons);

let obj = returnedPolygons2;
let entries = Object.entries(obj);
//console.log(entries);

			
			const data2 = [
                {
                    LATITUDE: 32.6735,
                    LONGITUDE: -83.2425,
                    TYPE: "National Monument",
                    NAME: "Cabrillo National Monument"
                },
                {
                    LATITUDE: 34.2234,
                    LONGITUDE: -79.5590,
                    TYPE: "National Monument",
                    NAME: "Cesar E. Chavez National Monument"
                },
                {
                    LATITUDE: 37.6251,
                    LONGITUDE: -82.0850,
                    TYPE: "National Monument",
                    NAME: "Devils Postpile National Monument"
                }
            ];
        
		
            // create an array of graphics based on the data above
            var graphics = [];
            var graphic;
			var rowcount = 0;
            for (var i=0; i < entries.length; i++){
                graphic = new Graphic({
                    geometry: {
                        type: "polygon"
                    },
                    attributes: entries[i]
                });
                graphics.push(graphic);
				rowcount = rowcount + 1;
				alert(JSON.stringify(graphic));
            }
			
			alert ("stringify Graphic: " + (JSON.stringify(graphics)));
			
			alert ("Rowcount: " + rowcount);
            // addEdits object tells applyEdits that you want to add the features
            const addEdits = {
                addFeatures: graphics
            };

			alert ("add edits: " + (JSON.stringify(addEdits)));
			
            // apply the edits to the layer
            applyEditsToLayer(addEdits);
        }

        function applyEditsToLayer(edits) {
		   alert("in applyEditsToLayer Function");
		   alert("edits results: " + (edits));
           monumentLayer
            .applyEdits(edits)
            .then(function(results) {
              // if edits were removed
              if (results.deleteFeatureResults.length > 0){
                console.log(
                  results.deleteFeatureResults.length,
                  "features have been removed"
                );
                //addBtn.disabled = false;
                //removeBtn.disabled = true;
              }
              // if features were added - call queryFeatures to return
              //    newly added graphics
              if (results.addFeatureResults.length > 0){
                var objectIds = [];
                results.addFeatureResults.forEach(function(item) {
                  objectIds.push(item.objectId);
                });
                // query the newly added features from the layer
                monumentLayer
                  .queryFeatures({
                    objectIds: objectIds
                  })
                  .then(function(results){
                    console.log(
                      results.features.length,
                      "features have been added."
                    );
                    //addBtn.disabled = true;
                    //removeBtn.disabled = false;
                  })
              }
            })
            .catch(function(error) {
              console.log(error);
            });
			
			zoompolygons();
        }


        // fires when "Remove Features" button clicked
        function removeFeatures(){
            // query for the features you want to remove
            monumentLayer.queryFeatures().then(function(results){
                // edits object tells apply edits that you want to delete the features
                const deleteEdits = {
                    deleteFeatures: results.features
                };
                // apply edits to the layer
                applyEditsToLayer(deleteEdits);
            });
        }

		
        }); // END OF MAIN FUNCTION
      </script>
    </head>

    <body>
	<div id="container">
      <div id="viewDiv"></div>
    	<div id="infoDiv" class="esri-widget">
			<div id="drop-downs">
			  Select Species type:
			  <select id="well-type" class="esri-widget"></select>
			</div>
			<button class="esri-button" id="remove">Remove 7 Features</button>
			<div id="results" class="esri-widget"></div>
		  </div>
	</div>
    </body>
  </html>

 

 

 

 

 

 

 

 

0 Kudos