Two map.on(("layers-add-result") functions.  How can I have both working?

3216
2
Jump to solution
10-04-2013 08:29 AM
ionarawilson1
Occasional Contributor III
I am combining two samples in one. One is the Editing without editor widget and the other is using the attribute inspector. However the attribute inspector is not working because both are using the map.on("layers-add-result"). They are:

    map.on("layers-add-result", initEditing);
    map.on("layers-add-result", initSelectToolbar);

How can I have both functions working  in my application? Thank you!

<!DOCTYPE html> <html>           ], function(         Map,Draw, BasemapGallery, arcgisUtils, Edit, Graphic,           ArcGISTiledMapServiceLayer, FeatureLayer, AttributeInspector,    Query, QueryTask,         SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Color,          TemplatePicker,          esriConfig, jsapiBundle,         arrayUtils, parser, domConstruct, Button, keys,  event, lang, registry,      borderContainer, contentPane, titlePane,         dom, on       ) {         parser.parse();                 // snapping is enabled for this sample - change the tooltip to reflect this         jsapiBundle.toolbars.draw.start = jsapiBundle.toolbars.draw.start +  "<br>Press <b>ALT</b> to enable snapping";                 // refer to "Using the Proxy Page" for more information:  https://developers.arcgis.com/en/javascript/jshelp/ags_proxy.html         esriConfig.defaults.io.proxyUrl = "/proxy";                    esriConfig.defaults.geometryService = new esri.tasks.GeometryService("http://tfsgis-iisd01:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer");                  map = new Map("map", {            basemap: "hybrid",                     center: [-98.57, 30.98],           zoom: 6,           slider: true          });           map.on("layers-add-result", initEditing);         map.on("layers-add-result", initSelectToolbar);           var ActivityArea = new FeatureLayer("http://tfsgis-iisd01:6080/arcgis/rest/services/MyMapService2/FeatureServer/1",{           mode: FeatureLayer.MODE_ONDEMAND,            outFields: ['*']         });          var ActivityPoint = new FeatureLayer("http://tfsgis-iisd01:6080/arcgis/rest/services/MyMapService2/FeatureServer/0",{           mode: FeatureLayer.MODE_ONDEMAND,            outFields: ['*']         });          var stewardship = new FeatureLayer("http://tfsgis-iisd01:6080/arcgis/rest/services/MyMapService2/FeatureServer/2",{           mode: FeatureLayer.MODE_ONDEMAND,            outFields: ['*']         });     var selectionSymbol = new SimpleFillSymbol(           SimpleFillSymbol.STYLE_NULL,            new SimpleLineSymbol(             "solid",              new Color("yellow"),              2           ),           null         );         stewardship.setSelectionSymbol(selectionSymbol);          stewardship.on("edits-complete", function() {                  });           map.addLayers([ActivityArea,ActivityPoint,stewardship]);       function initSelectToolbar(evt) {           var stewardship = evt.layers[0].layer;           var selectQuery = new Query();            map.on("click", function(evt) {             selectQuery.geometry = evt.mapPoint;             stewardship.selectFeatures(selectQuery, FeatureLayer.SELECTION_NEW, function(features) {               if (features.length > 0) {                //store the current feature                 updateFeature = features[0];                 map.infoWindow.setTitle(features[0].getLayer().name);                 map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor(evt.screenPoint));               } else {                 map.infoWindow.hide();               }             });           });            map.infoWindow.on("hide", function() {             stewardship.clearSelection();           });            var layerInfos = [{             'featureLayer': stewardship,             'showAttachments': false,             'isEditable': true,             'fieldInfos': [               {'fieldName': 'Office', 'isEditable':true, 'tooltip': 'Current Status', 'label':'Status:'},               {'fieldName': 'Forester', 'isEditable':true, 'tooltip': 'The name of this oil field', 'label':'Field Name:'},               {'fieldName': 'PlanID', 'isEditable':false,'label':'Acreage:'},               {'fieldName': 'Status', 'isEditable':false, 'label':'Average Depth:'},               {'fieldName': 'DateStart', 'isEditable':false, 'label':'Cummulative Oil:'},                          ]           }];            var attInspector = new AttributeInspector({             layerInfos:layerInfos           }, domConstruct.create("div"));                      //add a save button next to the delete button           var saveButton = new Button({ label: "Save", "class": "saveButton"});           domConstruct.place(saveButton.domNode, attInspector.deleteBtn.domNode, "after");                     saveButton.on("click", function(){             updateFeature.getLayer().applyEdits(null, [updateFeature], null);                    });                      attInspector.on("attribute-change", function(evt) {             //store the updates to apply when the save button is clicked               updateFeature.attributes[evt.fieldName] = evt.newFieldValue;           });                      attInspector.on("next", function(evt) {             updateFeature = evt.feature;             console.log("Next " + updateFeature.attributes.objectid);           });                      attInspector.on("delete", function(evt){             evt.feature.getLayer().applyEdits(null,null,[feature]);             map.infoWindow.hide();           });            map.infoWindow.setContent(attInspector.domNode);           map.infoWindow.resize(350, 240);         }            function initEditing(evt) {           console.log("initEditing", evt);           // var map = this;           var currentLayer = null;           var layers = arrayUtils.map(evt.layers, function(result) {             return result.layer;           });           console.log("layers", layers);            var editToolbar = new Edit(map);           editToolbar.on("deactivate", function(evt) {             currentLayer.applyEdits(null, [evt.graphic], null);           });            arrayUtils.forEach(layers, function(layer) {             var editingEnabled = false;             layer.on("dbl-click", function(evt) {               event.stop(evt);               if (editingEnabled === false) {                 editingEnabled = true;                 editToolbar.activate(Edit.EDIT_VERTICES , evt.graphic);               } else {                 currentLayer = this;                 editToolbar.deactivate();                 editingEnabled = false;               }             });              layer.on("click", function(evt) {               event.stop(evt);               if (evt.ctrlKey === true || evt.metaKey === true) {  //delete feature if ctrl key is depressed                 layer.applyEdits(null,null,[evt.graphic]);                 currentLayer = this;                 editToolbar.deactivate();                 editingEnabled=false;               }             });           });            var templatePicker = new TemplatePicker({             featureLayers: layers,             rows: "auto",             columns: 2,             grouping: true,             style: "height: auto; overflow: auto;"           }, "templatePickerDiv");            templatePicker.startup();            var drawToolbar = new Draw(map);            var selectedTemplate;           templatePicker.on("selection-change", function() {             if( templatePicker.getSelected() ) {               selectedTemplate = templatePicker.getSelected();             }             switch (selectedTemplate.featureLayer.geometryType) {               case "esriGeometryPoint":                 drawToolbar.activate(Draw.POINT);                 break;               case "esriGeometryPolyline":                 drawToolbar.activate(Draw.POLYLINE);                 break;               case "esriGeometryPolygon":                 drawToolbar.activate(Draw.POLYGON);                 break;             }           });            drawToolbar.on("draw-end", function(evt) {             drawToolbar.deactivate();             editToolbar.deactivate();             var newAttributes = lang.mixin({}, selectedTemplate.template.prototype.attributes);             var newGraphic = new Graphic(evt.geometry, null, newAttributes);             selectedTemplate.featureLayer.applyEdits([newGraphic], null, null);           });         }        });// end require     </script>   </head>   <body class="claro">     <div id="main" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline'" style="height:width:100%;height:100%;">       <div data-dojo-type="dijit/layout/ContentPane" id="header" data-dojo-props="region:'top'">        Spatial Accomplishment Report System       </div>           <div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'left'" style="width: 300px;overflow:hidden;">         <div id="templateDiv"></div>         <div id="templatePickerDiv"></div>        <br />     <br />  <div>      <button  id="button">Calculate</button>  </div>     <div id="info" style="padding:5px; margin:5px; background-color:#eee; height:680px;">
0 Kudos
1 Solution

Accepted Solutions
KenBuja
MVP Esteemed Contributor
Just combine the code from your two functions into a single function.

map.on("layers-add-result", layersAddResultHandler);  function layersAddResultHandler(evt) {          //initEditing code           console.log("initEditing", evt);           // var map = this;           var currentLayer = null;           var layers = arrayUtils.map(evt.layers, function(result) {             return result.layer;           });           console.log("layers", layers);            //etc            //initSelectToolbar code           var stewardship = evt.layers[0].layer;           var selectQuery = new Query();            //etc. }

View solution in original post

0 Kudos
2 Replies
KenBuja
MVP Esteemed Contributor
Just combine the code from your two functions into a single function.

map.on("layers-add-result", layersAddResultHandler);  function layersAddResultHandler(evt) {          //initEditing code           console.log("initEditing", evt);           // var map = this;           var currentLayer = null;           var layers = arrayUtils.map(evt.layers, function(result) {             return result.layer;           });           console.log("layers", layers);            //etc            //initSelectToolbar code           var stewardship = evt.layers[0].layer;           var selectQuery = new Query();            //etc. }
0 Kudos
ionarawilson1
Occasional Contributor III
Thank you Ken. I actually got it to work. But I think this is very important to know. I have needed before and I am sure I will need to know this in the future. Here is my script if anybody needs it:

      require([
        "esri/map",
        "esri/layers/FeatureLayer",
        "esri/dijit/AttributeInspector",

        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "dojo/_base/Color",

        "esri/layers/ArcGISDynamicMapServiceLayer",
        "esri/config",

        "esri/tasks/query",

        "dojo/parser", 
        "dojo/dom-construct",
        "dijit/form/Button",

        "dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dojo/domReady!"
      ], function(
        Map, FeatureLayer, AttributeInspector,
        SimpleLineSymbol, SimpleFillSymbol, Color,
        ArcGISDynamicMapServiceLayer, esriConfig,
        Query,
        parser, domConstruct, Button
      ) {
        parser.parse();

        // refer to "Using the Proxy Page" for more information:  https://developers.arcgis.com/en/javascript/jshelp/ags_proxy.html
        esriConfig.defaults.io.proxyUrl = "/proxy";

        map = new Map("mapDiv", {
          basemap: "streets",
          center: [-97.395, 37.537],
          zoom: 11
        });
        
        map.on("layers-add-result", initSelectToolbar);

        var petroFieldsMSL = new ArcGISDynamicMapServiceLayer("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Petroleum/KSFields/MapServer");
        petroFieldsMSL.setDisableClientCaching(true);
        map.addLayer(petroFieldsMSL);

        var petroFieldsFL = new FeatureLayer("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Petroleum/KSFields/FeatureServer/0", {
          mode: FeatureLayer.MODE_SELECTION,
          outFields: ["approxacre","objectid","field_name","activeprod","cumm_oil","cumm_gas","avgdepth"]
        });
        var selectionSymbol = new SimpleFillSymbol(
          SimpleFillSymbol.STYLE_NULL, 
          new SimpleLineSymbol(
            "solid", 
            new Color("yellow"), 
            2
          ),
          null
        );
        petroFieldsFL.setSelectionSymbol(selectionSymbol);

        petroFieldsFL.on("edits-complete", function() {
          petroFieldsMSL.refresh();
        });

        map.addLayers([petroFieldsFL]);

        function initSelectToolbar(evt) {
          var petroFieldsFL = evt.layers[0].layer;
          var selectQuery = new Query();

          map.on("click", function(evt) {
            selectQuery.geometry = evt.mapPoint;
            petroFieldsFL.selectFeatures(selectQuery, FeatureLayer.SELECTION_NEW, function(features) {
              if (features.length > 0) {
               //store the current feature
                updateFeature = features[0];
                map.infoWindow.setTitle(features[0].getLayer().name);
                map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor(evt.screenPoint));
              } else {
                map.infoWindow.hide();
              }
            });
          });

          map.infoWindow.on("hide", function() {
            petroFieldsFL.clearSelection();
          });

          var layerInfos = [{
            'featureLayer': petroFieldsFL,
            'showAttachments': false,
            'isEditable': true,
            'fieldInfos': [
              {'fieldName': 'activeprod', 'isEditable':true, 'tooltip': 'Current Status', 'label':'Status:'},
              {'fieldName': 'field_name', 'isEditable':true, 'tooltip': 'The name of this oil field', 'label':'Field Name:'},
              {'fieldName': 'approxacre', 'isEditable':false,'label':'Acreage:'},
              {'fieldName': 'avgdepth', 'isEditable':false, 'label':'Average Depth:'},
              {'fieldName': 'cumm_oil', 'isEditable':false, 'label':'Cummulative Oil:'},
              {'fieldName': 'cumm_gas', 'isEditable':false, 'label':'Cummulative Gas:'}
            ]
          }];

          var attInspector = new AttributeInspector({
            layerInfos:layerInfos
          }, domConstruct.create("div"));
          
          //add a save button next to the delete button
          var saveButton = new Button({ label: "Save", "class": "saveButton"});
          domConstruct.place(saveButton.domNode, attInspector.deleteBtn.domNode, "after");
         
          saveButton.on("click", function(){
            updateFeature.getLayer().applyEdits(null, [updateFeature], null);         
          });
          
          attInspector.on("attribute-change", function(evt) {
            //store the updates to apply when the save button is clicked 
             updateFeature.attributes[evt.fieldName] = evt.newFieldValue;
          });
          
          attInspector.on("next", function(evt) {
            updateFeature = evt.feature;
            console.log("Next " + updateFeature.attributes.objectid);
          });
          
          attInspector.on("delete", function(evt){
            evt.feature.getLayer().applyEdits(null,null,[feature]);
            map.infoWindow.hide();
          });

          map.infoWindow.setContent(attInspector.domNode);
          map.infoWindow.resize(350, 240);
        }
0 Kudos