How to create a Buffer on a button click with a specific radius and to highlight the features in that specified radius?

983
3
09-28-2020 11:01 PM
SteffiAntony
New Contributor

This is my code  please do help me to create a buffer on click on map and to highlight the features across that distance(eg:5km).

var maptoolbar;
var identifyTaskidentifyParams;
require([
  "esri/map",
  "esri/layers/ArcGISDynamicMapServiceLayer",
  "esri/layers/GraphicsLayer",

  "esri/layers/FeatureLayer",
  "esri/dijit/FeatureTable",
  "esri/tasks/query",
  "esri/symbols/PictureMarkerSymbol",

  "esri/tasks/QueryTask",

  "esri/dijit/Legend",
  "esri/dijit/LayerList",
  "dojo/_base/array",

  "esri/toolbars/draw",
  "esri/graphic",
  "esri/symbols/SimpleMarkerSymbol",
  "esri/symbols/SimpleLineSymbol",
  "esri/symbols/SimpleFillSymbol",
  "esri/Color",
  "esri/toolbars/edit",

  "esri/tasks/IdentifyTask",
  "esri/tasks/IdentifyParameters",
  "esri/dijit/Popup",
  "esri/InfoTemplate",
  "dojo/dom-construct",

  "dojo/_base/event",
  "dojo/parser",
  "dijit/registry",

  "dojo/on""dojo/dom",
  "dijit/layout/BorderContainer",
  "dijit/layout/ContentPane",
  "dijit/layout/AccordionContainer",
  "dijit/WidgetSet",
  "dojo/domReady!"
], function (
  MapArcGISDynamicMapServiceLayerGraphicsLayer,
  FeatureLayerFeatureTableQueryPictureMarkerSymbol,
  QueryTask,
  LegendLayerListarrayUtils,
  DrawGraphicSimpleMarkerSymbolSimpleLineSymbolSimpleFillSymbolColorEdit,
  IdentifyTaskIdentifyParametersPopupInfoTemplatedomConstruct,
  eventparserregistry,
  ondom,
) {
  parser.parse();

  var popup = new Popup({
    fillSymbol: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
      new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
        new Color([25500]), 2), new Color([25525500.25]))
  }, domConstruct.create("div"));

  map = new Map("map", {
    basemap: "dark-gray",
    sliderOrientation: "horizontal",
    infoWindow: popup
  });

  // user adding mapurl
  var mybutton = dom.byId("mybutton"),
    textbox = dom.byId("myInput");
  on(mybutton"click"function (evt) {
    var dynamicLayer = new ArcGISDynamicMapServiceLayer(textbox.value);
    map.addLayers([dynamicLayer]);
  });

  //Adding 3 graphics layers//
  var PointLayer = new GraphicsLayer();
  map.addLayer(PointLayer);
  var LineLayer = new GraphicsLayer();
  map.addLayer(LineLayer);
  var PolygonLayer = new GraphicsLayer();
  map.addLayer(PolygonLayer);

  map.on("layers-add-result"function (evt) {
    // console.log(evt);
    var layerInfo = arrayUtils.map(evt.layersfunction (layerindex) {
      return { layer: layer.layertitle: layer.layer.name };
    });
    map.setExtent(evt.layers[0].layer.initialExtent);
    if (layerInfo.length > 0) {
      //add the layers
      var layerListWidjet = new LayerList({
        map: map,
        layerInfos: layerInfo
      }, "layerListDom");
      layerListWidjet.startup();
      //add legend
      var legendDijit = new Legend({
        map: map,
        layerInfos: layerInfo
      }, "legendDiv");
      legendDijit.startup();
    }
  });
  map.on("load"createToolbar);
  // loop through all dijits, connect onClick event
  // listeners for buttons to activate drawing tools
  registry.forEach(function (d) {
    // d is a reference to a dijit
    // could be a layout container or a button
    if (d.declaredClass === "dijit.form.Button") {
      d.on("click"activateTool);
    }
  });
  function activateTool() {
    var tool = this.label.toUpperCase().replace(/ /g"_");
    toolbar.activate(Draw[tool]);
    map.hideZoomSlider();
  }
  function createToolbar() {
    toolbar = new Draw(map);
    toolbar.on("draw-end"addToMap);
    createToolbars();
  }
  function addToMap(evt) {
    toolbar.deactivate();
    map.showZoomSlider();
    //SimpleMarkerSymbol
    var marker = new SimpleMarkerSymbol();
    marker.setColor(new Color([01972551]));
    marker.setSize(20);
    marker.setPath("M16,3.5c-4.142,0-7.5,3.358-7.5,7.5c0,4.143,7.5,18.121,7.5,18.121S23.5,15.143,23.5,11C23.5,6.858,20.143,3.5,16,3.5z M16,14.584c-1.979,0-3.584-1.604-3.584-3.584S14.021,7.416,16,7.416S19.584,9.021,19.584,11S17.979,14.584,16,14.584z");
    marker.setStyle(SimpleMarkerSymbol.STYLE_PATH);
    //SimpleLineSymbol
    var line = new SimpleLineSymbol();
    line.setColor(new Color([0761151]));
    //SimpleFillSymbol
    var fill = new SimpleFillSymbol();
    fill.setColor(new Color([7623000.4]));
    if (evt.geometry.type === "point" || evt.geometry.type === "multipoint") {
      PointLayer.add(new Graphic(evt.geometrymarker));
    } else if (evt.geometry.type === "line" || evt.geometry.type === "polyline") {
      LineLayer.add(new Graphic(evt.geometryline));
    }
    else {
      PolygonLayer.add(new Graphic(evt.geometryfill));
    }
  }
  function createToolbars() {
    editToolbar = new Edit(map);
    //Activate the toolbar when you click on a graphic
    PointLayer.on("click"editgraphics);
    PolygonLayer.on("click"editgraphics);
    LineLayer.on("click"editgraphics);
    function editgraphics(evt) {
      event.stop(evt);
      activateToolbar(evt.graphic);
    };

    //deactivate the toolbar when you click outside a graphic
    map.on("click"function (evt) {
      editToolbar.deactivate();
    });
  }
  function activateToolbar(graphic) {
    var tool = 0;
    tool = tool | Edit.MOVE;
    tool = tool | Edit.EDIT_VERTICES;
    tool = tool | Edit.SCALE;
    tool = tool | Edit.ROTATE;
    // enable text editing if a graphic uses a text symbol
    if (graphic.symbol.declaredClass === "esri.symbol.TextSymbol") {
      tool = tool | Edit.EDIT_TEXT;
    }
    // specify toolbar options        
    var options = {
      allowAddVertices: true,
      allowDeleteVertices: true,
      uniformScaling: true
    };
    editToolbar.activate(toolgraphicoptions);
  }
  ///// Load Table Grid  ///////
  // editable FeatureLayer
  var myFeatureLayer = new FeatureLayer("https://services.arcgis.com/V6ZHFr6zdgNZuVG0/ArcGIS/rest/services/Warren_College_Trees/FeatureServer/0", {
    mode: FeatureLayer.MODE_ONDEMAND,
    outFields: ["*"],
    visible: true,
    editable: true,
    id: "fLayer2"
  });
  var fieldInfoslist = [];
  myFeatureLayer.on("load"function () {
    map.setExtent(myFeatureLayer.initialExtent);
    for (i = 0i < myFeatureLayer.fields.lengthi++) {
      //write out field info   
      // console.log(dojoJson.toJson(myFeatureLayer.fields));    
      var fields = {
        name: myFeatureLayer.fields[i].name,
        alias: myFeatureLayer.fields[i].alias,
        type: myFeatureLayer.fields[i].type
      }
      fieldInfoslist.push(fields);
    }
  });
  // console.log(fieldInfoslist);
  // set a selection symbol for the featurelayer
  var selectionSymbol = new PictureMarkerSymbol();
  selectionSymbol.setWidth(30);
  selectionSymbol.setHeight(30);
  selectionSymbol.setUrl("http://www.clker.com/cliparts/e/W/i/N/R/X/localize-me-red-marker-md.png");

  myFeatureLayer.setSelectionSymbol(selectionSymbol);

  // listen to featurelayer click event to handle selection 
  // from layer to the table. 
  // when user clicks on a feature on the map, the corresponding 
  // record will be selected in the table.   
  myFeatureLayer.on("click"function (evt) {
    var idProperty = myFeatureLayer.objectIdField,
      feature,
      featureId,
      query;

    if (evt.graphic && evt.graphic.attributes && evt.graphic.attributes[idProperty]) {
      feature = evt.graphic,
        featureId = feature.attributes[idProperty];

      query = new Query();
      query.returnGeometry = false;
      query.objectIds = [featureId];
      query.where = "1=1";

      myFeatureLayer.selectFeatures(queryFeatureLayer.SELECTION_NEW);
    }
  });

  // Redlands police vehicle locations layer
  // this layer is an editable layer 
  map.addLayer(myFeatureLayer);

  //create new FeatureTable and set its properties 
  var gridbutton = dom.byId("grid")
  on(gridbutton"click"function (evt) {

    var myFeatureTable = new FeatureTable({
      featureLayer: myFeatureLayer,
      map: map,
      editable: true,
      syncSelection: true,
      dateOptions: {
        datePattern: 'M/d/y',
        timeEnabled: true,
        timePattern: 'H:mm',
      },
      // use fieldInfos object to change field's label (column header), 
      // change the editability of the field, and to format how field values are displayed
      // you will not be able to edit callnumber field in this example. 
      fieldInfos: [],
    }, 'myTableNode');

    // console.log(myFeatureLayer);

    myFeatureTable.startup();
  });
  // function loadQueryTask() {
  var queryTask = new QueryTask("https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1");

  var query = new Query();
  query.returnGeometry = true;
  query.outFields = ["*"];
  on(dom.byId("execute"), "click"execute);

  function execute() {
    query.outSpatialReference = map.spatialReference;
    query.text = dom.byId("stateName").value;
    queryTask.execute(queryshowResults);
  }

  function showResults(results) {
    var resultItems = [];
    var resultCount = results.features.length;
    for (var i = 0i < resultCounti++) {
      var feature = results.features[i];
      var featureAttributes = feature.attributes;
      for (var attr in featureAttributes) {
        resultItems.push("<b>" + attr + ":</b>  " + featureAttributes[attr] + "<br>");
      }

      var simpleFillSymbol = new SimpleFillSymbol().setColor(new Color([50205500.25]));
      var polygonGraphic = new Graphic(feature.geometrysimpleFillSymbol);
      resultItems.push("<br>"); debugger
      map.graphics.add(polygonGraphic);
      // map.centerAndZoom(feature, 12);  
    }
    dom.byId("info").innerHTML = resultItems.join("");
  }

  //////////////////// Identify Task ///////////////
  var identifyButton = dom.byId("identify")
  on(identifyButton"click"function (evt) {
    identifyClickHandler = on(map'click'executeIdentifyTask);
    identifyTask = new IdentifyTask(textbox.value);

    identifyParams = new IdentifyParameters();
    identifyParams.tolerance = 3;
    identifyParams.returnGeometry = true;
    identifyParams.layerIds = [02];
    identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
    identifyParams.width = map.width;
    identifyParams.height = map.height;
  })
  function executeIdentifyTask(event) {
    identifyParams.geometry = event.mapPoint;
    identifyParams.mapExtent = map.extent;

    var deferred = identifyTask
      .execute(identifyParams)
      .addCallback(function (response) {
        return arrayUtils.map(responsefunction (result) {
          var feature = result.feature;
          var layerName = result.layerName;

          feature.attributes.layerName = layerName;
          // console.log(feature.attributes);
          var Templates = new InfoTemplate("");
          feature.setInfoTemplate(Templates);

          return feature;
        });
      });
    map.infoWindow.setFeatures([deferred]);
    map.infoWindow.show(event.mapPoint);
    identifyClickHandler.remove();
  }
});
0 Kudos
3 Replies
RobertScheitlin__GISP
MVP Emeritus

Steffi,

   In your activateTool function you just need to handle the buffer button.

  function activateTool() {
    var tool = this.label.toUpperCase().replace(/ /g, "_");
    if(tool === 'Buffer'){
      //goto your buffer function
    }else{
      toolbar.activate(Draw[tool]);
    }
    map.hideZoomSlider();
  }
0 Kudos
SteffiAntony
New Contributor

can you please provide me a sample code for buffer functionality???

0 Kudos
RobertScheitlin__GISP
MVP Emeritus
          var Buffers = geometryEngine.geodesicBuffer(Point20"meters"true);
          Buffer = Buffers[0];