Select to view content in your preferred language

Switch statement JS

7880
32
Jump to solution
05-27-2014 10:34 AM
AlexGole1
Emerging Contributor
Hi all,
I am trying to create a GIS data portal that allows users to select one out three diffent methods for data extraction.
1) extract by graphic extent
2) extract by extent of a county
3) extract by unit (calfire)

Here is my problem. I am using a switch statement that allow the users to select either one of these methods independently as shown on this thread.

However, when I trigger the either one of the cases within my function by pushing on a download button. It seems like the GPtool cant access any input data for some reasons.

errors I get for each of the functions described above :
TypeError: Unable to get property 'geometry' of undefined or null reference  TypeError: Unable to get property 'style' of undefined or null reference  TypeError: Unable to get property 'style' of undefined or null reference


My code:
var extractMethod = "extractByPoly";    var extractMethod = "extractByCounty";    var extractMethod = "extractByUnit";        function myFunction() {     //var extractMethod = "extractByPoly";     //var extractMethod = "extractByCounty";     //var extractMethod = "extractByUnit";      switch (extractMethod) {         default:              //function extractData() {             //get clip layers             var clipLayers = [];             if (registry.byId("layer1").get("checked")) {                 clipLayers.push("SRA");             }             if (registry.byId("layer2").get("checked")) {                 clipLayers.push("Burn");             }             if (clipLayers.length === 0 || map.graphics.graphics.length === 0) {                 alert("Select layers to extract and draw an area of interest.");                 return;             }              var featureSet = new FeatureSet();             var features = [];             features.push(map.graphics.graphics[0]);             featureSet.features = features;              var params3 = {                 "Layers_to_Clip": clipLayers,                 "Area_of_Interest": featureSet,                 "Feature_Format": registry.byId("formatBox").get("value")             };              domStyle.set(loading2, "display", "inline-block");             gp.submitJob(params3, completeCallback, statusCallback2, function (error) {                 alert(error);                 domStyle.set(loading2, "display", "none");             });             //}             break;          case "extractByCounty":             //function executeQueryTask(county) {             var clipLayers = [];             if (registry.byId("layer1").get("checked")) {                 clipLayers.push("SRA");             }             if (registry.byId("layer2").get("checked")) {                 clipLayers.push("Burn");             }             if (clipLayers.length === 0) {                 alert("No layers to clip, please select a layer you would like to clip...");                 return;             }              var county = document.getElementById("sel_county").value             var unit = document.getElementById("sel_unit").value             var queryTask = new QueryTask("http://webgisdevint1/arcgis/rest/services/Alex_Try/Counties/MapServer/0");                                       var query = new Query();             query.returnGeometry = true;             query.outFields = ["NAME_PCASE"];             query.where = "NAME_PCASE = '" + county + "'";             query.outSpatialReference = map.spatialReference;             queryTask.execute(query, function (featureSet) {                 var AOI = featureSet.features[0].geometry;                 var graphic = new Graphic(AOI);                 var features = [];                 features.push(graphic);                 var fSet = new FeatureSet();                 fSet.features = features;                   var params = {                     "Layers_to_Clip": clipLayers,                     "Area_of_Interest": fSet,                     "Feature_Format": registry.byId("formatBox").get("value")                 };                    domStyle.set(loading, "display", "inline-block");                 gp.submitJob(params, completeCallback, statusCallback, function (error) {                     alert(error);                     domStyle.set(loading, "display", "none");                 });             });             //}             break;           case "extractByUnit":             //function executeQueryTask1(unit) {             var clipLayers = [];             if (registry.byId("layer1").get("checked")) {                 clipLayers.push("SRA");             }             if (registry.byId("layer2").get("checked")) {                 clipLayers.push("Burn");             }             if (clipLayers.length === 0) {                 alert("No layers to clip, please select a layer you would like to clip...");                 return;             }              var unit = document.getElementById("sel_unit").value             var queryTask = new QueryTask("http://webgisdevint1/arcgis/rest/services/Alex_Try/Layers/MapServer/1");                          var query = new Query();             query.returnGeometry = true;             query.outFields = ["UNITCODE"];             query.where = "UNITCODE = '" + unit + "'";             query.outSpatialReference = map.spatialReference;             queryTask.execute(query, function (featureSet) {                 var AOI = featureSet.features[0].geometry;                 var graphic = new Graphic(AOI);                 var features = [];                 features.push(graphic);                 var fSet = new FeatureSet();                 fSet.features = features;                   var params2 = {                     "Layers_to_Clip": clipLayers,                     "Area_of_Interest": fSet,                     "Feature_Format": registry.byId("formatBox").get("value")                 };                    domStyle.set(loading1, "display", "inline-block");                 gp.submitJob(params2, completeCallback, statusCallback1, function (error) {                     alert(error);                     domStyle.set(loading1, "display", "none");                 });             });             //}     } }


Any idea why I get these errors?
0 Kudos
32 Replies
SteveCole
Honored Contributor
Ah. so I remove the following code before the query?  
var unit = document.getElementById("sel_unit").value


No- leave that. Otherwise, you won't know what Unit the user has selected. The code I posted for the listener is ONLY for keeping track of what the user does (they drew a polygon so extract by polygon, they selected a unit from the combo box so extract by unit, etc). Hopefully you see that the variable extractMethod is constantly populated and overwritten every time the user does one of those three things- draw a shape, select an item in the County combo box, or select a Unit in the Unit combo box.

In theory, the Extract button (and the switch statement) will look at what the most recent value for extractMethod is. You could do all three options and if you last drew a polygon, that's what the switch statement should act on.

Your follow up post makes me wonder if the change event is "change" or "onChange". Here's a simple test to see whether or not the listener is properly set up. Add the following line of code inside the function:
        registry.byId("sel_county").on("change", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        registry.byId("sel_unit").on("change", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });


Watch the console when you pick an item from either combo box. You should see the statement show up once you select an item. If it's not, then there's something off with my event code, either I have the wrong event name or something else. Try this and post what you observe.
0 Kudos
AlexGole1
Emerging Contributor
No- leave that. Otherwise, you won't know what Unit the user has selected. The code I posted for the listener is ONLY for keeping track of what the user does (they drew a polygon so extract by polygon, they selected a unit from the combo box so extract by unit, etc). Hopefully you see that the variable extractMethod is constantly populated and overwritten every time the user does one of those three things- draw a shape, select an item in the County combo box, or select a Unit in the Unit combo box. 

In theory, the Extract button (and the switch statement) will look at what the most recent value for extractMethod is. You could do all three options and if you last drew a polygon, that's what the switch statement should act on. 

Your follow up post makes me wonder if the change event is "change" or "onChange". Here's a simple test to see whether or not the listener is properly set up. Add the following line of code inside the function: 
        registry.byId("sel_county").on("change", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        registry.byId("sel_unit").on("change", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });


Watch the console when you pick an item from either combo box. You should see the statement show up once you select an item. If it's not, then there's something off with my event code, either I have the wrong event name or something else. Try this and post what you observe.


Alright I tried but nothing happens. The console shows no statements like :"You are selecting a unit!" I tried both, change and onChange methods.

Here is my code
   registry.byId("stop").on("click", function () {
   map.graphics.clear();
            selectionToolbar.deactivate();
          });
  
  registry.byId("polygon").on("click", function () {
            activateTool(this.id);
         });

        registry.byId("freehandpolygon").on("click", function () {
            activateTool(this.id);
         });
   
   registry.byId("extract").on("click", myFunction);
   
   
   registry.byId("sel_county").on("onChange", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        registry.byId("sel_unit").on("onChange", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });

   
  
   function initSelectionToolbar() {
            map.graphics.clear();

            selectionToolbar = new Draw(map);
            selectionToolbar.on("draw-end", function (e) {
               selectionToolbar.deactivate();

               var symbol3 = new SimpleFillSymbol(
                  "solid",
                  new SimpleLineSymbol("dash", new Color([255, 0, 0]), 2),
                  new Color([255, 255, 0, 0.25])
               );

               var graphic = new Graphic(e.geometry, symbol3);
               map.graphics.add(graphic);
      extractMethod = "extractByPoly";
            });
         }

         function activateTool(tool) {
            map.graphics.clear();
            // The draw.activate expects a string like "polygon" or "freehand_polygon".
            selectionToolbar.activate(tool);
         }
  
   
   
   function myFunction() {
    //var extractMethod = "extractByPoly";
    //var extractMethod = "extractByCounty";
    //var extractMethod = "extractByUnit";

    switch (extractMethod) {
        default:

            //function extractData() {
            //get clip layers
            var clipLayers = [];
            if (registry.byId("layer1").get("checked")) {
                clipLayers.push("SRA");
            }
            if (registry.byId("layer2").get("checked")) {
                clipLayers.push("Burn");
            }
            if (clipLayers.length === 0 || map.graphics.graphics.length === 0) {
                alert("Select layers to extract and draw an area of interest.");
                return;
            }

            var featureSet = new FeatureSet();
            var features = [];
            features.push(map.graphics.graphics[0]);
            featureSet.features = features;

            var params3 = {
                "Layers_to_Clip": clipLayers,
                "Area_of_Interest": featureSet,
                "Feature_Format": registry.byId("formatBox").get("value")
            };

            domStyle.set(loading2, "display", "inline-block");
            gp.submitJob(params3, completeCallback, statusCallback2, function (error) {
                alert(error);
                domStyle.set(loading2, "display", "none");
            });
            //}
            break;

        case "extractByCounty":
            //function executeQueryTask(county) {
            var clipLayers = [];
            if (registry.byId("layer1").get("checked")) {
                clipLayers.push("SRA");
            }
            if (registry.byId("layer2").get("checked")) {
                clipLayers.push("Burn");
            }
            if (clipLayers.length === 0) {
                alert("No layers to clip, please select a layer you would like to clip...");
                return;
            }
   
   
   var county = document.getElementById("sel_county").value
            var queryTask = new QueryTask("http://webgisdevint1/arcgis/rest/services/Alex_Try/Counties/MapServer/0");
            var query = new Query();
            query.returnGeometry = true;
            query.outFields = ["NAME_PCASE"];
            query.where = "NAME_PCASE = '" + extractMethod + "'";
            query.outSpatialReference = map.spatialReference;
            queryTask.execute(query, function (featureSet) {
       if (featureSet.features.length === 0) {
                     alert("Query task did not return any features");
                 return;
                } else {
                var AOI = featureSet.features[0].geometry;
                var graphic = new Graphic(AOI, symbol);
                var features = [];
                features.push(graphic);
                var fSet = new FeatureSet();
                fSet.features = features;


                var params = {
                    "Layers_to_Clip": clipLayers,
                    "Area_of_Interest": fSet,
                    "Feature_Format": registry.byId("formatBox").get("value")
                };



                domStyle.set(loading, "display", "inline-block");
                gp.submitJob(params, completeCallback, statusCallback, function (error) {
                    alert(error);
                    domStyle.set(loading, "display", "none");
                });
    }
            });
   
   
            //}
            break;


        case "extractByUnit":
            //function executeQueryTask1(unit) {
            var clipLayers = [];
            if (registry.byId("layer1").get("checked")) {
                clipLayers.push("SRA");
            }
            if (registry.byId("layer2").get("checked")) {
                clipLayers.push("Burn");
            }
            if (clipLayers.length === 0) {
                alert("No layers to clip, please select a layer you would like to clip...");
                return;
            }
   
   
            
   var unit = document.getElementById("sel_unit").value
            var queryTask = new QueryTask("http://webgisdevint1/arcgis/rest/services/Alex_Try/Layers/MapServer/1");
            var query = new Query();
            query.returnGeometry = true;
            query.outFields = ["UNITCODE"];
            query.where = "UNITCODE = '" + extractMethod + "'";
            query.outSpatialReference = map.spatialReference;
            queryTask.execute(query, function (featureSet) {
                 if (featureSet.features.length === 0) {
                     alert("Query task did not return any features");
                 return;
                } else {
    var AOI = featureSet.features[0].geometry;
                var graphic = new Graphic(AOI, symbol);
                var features = [];
                features.push(graphic);
                var fSet = new FeatureSet();
                fSet.features = features;


                var params2 = {
                    "Layers_to_Clip": clipLayers,
                    "Area_of_Interest": fSet,
                    "Feature_Format": registry.byId("formatBox").get("value")
                };



                domStyle.set(loading1, "display", "inline-block");
                gp.submitJob(params2, completeCallback, statusCallback1, function (error) {
                    alert(error);
                    domStyle.set(loading1, "display", "none");
                });
    }
            });
            //}
   break;
    
 }
}
0 Kudos
SteveCole
Honored Contributor
Ok, that's helpful. The event listener I gave you isn't firing. Alter the code slightly as shown below:
        dom.byId("sel_county").on("change", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        dom.byId("sel_unit").on("change", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });
0 Kudos
AlexGole1
Emerging Contributor
Ok, that's helpful. The event listener I gave you isn't firing. Alter the code slightly as shown below: 
        dom.byId("sel_county").on("change", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        dom.byId("sel_unit").on("change", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });


Sorry to keep posting Steve. Now I get the following error:
TypeError: dom.byId(...).on is not a function
0 Kudos
SteveCole
Honored Contributor
No worries. Let's try this instead:
        on(dom.byId("sel_county"), "change", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        on(dom.byId("sel_unit"), "change", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });
0 Kudos
AlexGole1
Emerging Contributor
No worries. Let's try this instead:
        on(dom.byId("sel_county"), "change", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        on(dom.byId("sel_unit"), "change", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });


No errors this time but the listener is still no firing up. I dont get "You are selecting a unit!"

on(dom.byId("sel_county"), "change", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        on(dom.byId("sel_unit"), "change", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });

   
  
   function initSelectionToolbar() {
            map.graphics.clear();

            selectionToolbar = new Draw(map);
            selectionToolbar.on("draw-end", function (e) {
               selectionToolbar.deactivate();

               var symbol3 = new SimpleFillSymbol(
                  "solid",
                  new SimpleLineSymbol("dash", new Color([255, 0, 0]), 2),
                  new Color([255, 255, 0, 0.25])
               );

               var graphic = new Graphic(e.geometry, symbol3);
               map.graphics.add(graphic);
      extractMethod = "extractByPoly";
            });
         }

         function activateTool(tool) {
            map.graphics.clear();
            // The draw.activate expects a string like "polygon" or "freehand_polygon".
            selectionToolbar.activate(tool);
         }
  
   
   
   function myFunction() {
    //var extractMethod = "extractByPoly";
    //var extractMethod = "extractByCounty";
    //var extractMethod = "extractByUnit";

    switch (extractMethod) {
        default:

            //function extractData() {
            //get clip layers
            var clipLayers = [];
            if (registry.byId("layer1").get("checked")) {
                clipLayers.push("SRA");
            }
            if (registry.byId("layer2").get("checked")) {
                clipLayers.push("Burn");
            }
            if (clipLayers.length === 0 || map.graphics.graphics.length === 0) {
                alert("Select layers to extract and draw an area of interest.");
                return;
            }

            var featureSet = new FeatureSet();
            var features = [];
            features.push(map.graphics.graphics[0]);
            featureSet.features = features;

            var params3 = {
                "Layers_to_Clip": clipLayers,
                "Area_of_Interest": featureSet,
                "Feature_Format": registry.byId("formatBox").get("value")
            };

            domStyle.set(loading2, "display", "inline-block");
            gp.submitJob(params3, completeCallback, statusCallback2, function (error) {
                alert(error);
                domStyle.set(loading2, "display", "none");
            });
            //}
            break;
0 Kudos
SteveCole
Honored Contributor
Ok, I *think* this is it. 😄

Substitute onChange for Change:
        on(dom.byId("sel_county"), "onChange", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        on(dom.byId("sel_unit"), "onChange", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });
0 Kudos
AlexGole1
Emerging Contributor
Ok, I *think* this is it. 😄 

Substitute onChange for Change: 
        on(dom.byId("sel_county"), "onChange", function () {
            extractMethod = "extractByCounty";
            console.log("You are selecting a county!");
         });

        on(dom.byId("sel_unit"), "onChange", function () {
            extractMethod = "extractByUnit";
            console.log("You are selecting a unit!");
         });


🙂 well I cant start the app anymore Here is what I get.[ATTACH=CONFIG]34145[/ATTACH]

Maybe the combobox should be created in JS not html like this http://jsfiddle.net/phusick/Hp5jr/ ?? It seems like the script works fine in ie11 not Mozilla, but the listener still does not fire up for some reasons
0 Kudos
SteveCole
Honored Contributor
Can you refresh the code in your jsbin link with what you now have?

I don't think that having the combo boxes created on the HTML side instead of the JS side should matter. Something else must be going on.

This is probably a non-factor but I would change your opening <style> HTML tag at the top to this:
[HTML]<style type="text/css">[/HTML]
0 Kudos
AlexGole1
Emerging Contributor
Can you refresh the code in your jsbin link with what you now have?

I don't think that having the combo boxes created on the HTML side instead of the JS side should matter. Something else must be going on.

This is probably a non-factor but I would change your opening <style> HTML tag at the top to this:
[HTML]<style type="text/css">[/HTML]


http://jsbin.com/tifuw/2/edit

I have my stylesheet on a seperate stylesheet on my computer
0 Kudos