Combine two Examples with Buttons to activate code

5162
39
Jump to solution
04-01-2014 08:18 AM
jaykapalczynski
Honored Contributor
I am combining a few examples from the JS API. I am trying to make them only active when a button is clicked.
On Load neither are active. I click my identify button and it identifies. I then click my Buffer Button and it runs the buffer code, buffers and returns results to a grid.
It does not appear that the identify is working after the Buffer button is clicked (perfect)
But after I run the Buffer Tool and click back to the identify it still runs the Buffer Code....

I am looking for a way to "turn it off" the buffer code when I click the Identify button. (for a lack of better words)

I am not sure where I can:
1. Turn off the Buffer Tool - I tough of putting some sort of code in the IDENTIFY BUTTON code to disable it?
2. Remove the graphics from the feature layer that were created when the selection occurs from the buffer

 on(dom.byId("IDENTIFY"), "click", function () {
        initializeSidebar(app.map);
 //Clear Graphic Circle from BufferTool
 app.map.graphics.clear();
 clearContent();
 // CLOSE THE PANE WHEN SELECTED
 dijit.byId("Tools").set('open',false); //Close
  })


  on(dom.byId("BUFFER"), "click", function () {
 dom.byId("featureCount").innerHTML = "Click Identify Tool to select feature(s)";
        featureLayer0.setInfoTemplate(null);
        featureLayer1.setInfoTemplate(null);
        app.map.infoWindow.hide();
        clearContent();

        // CLOSE THE PANE WHEN SELECTED
 dijit.byId("Tools").set('open',false); //Close

 BufferTool(app.map);
   })



Function BufferTool
    function BufferTool(map){

        dialog = new TooltipDialog({
          id: "tooltipDialog",
          style: "position: absolute; width: 100px; font: normal normal normal 10pt Helvetica;z-index:100"
        });
        dialog.startup();

       // selection symbol used to draw the selected census block points within the buffer polygon
        var point = new SimpleMarkerSymbol(
          SimpleMarkerSymbol.STYLE_CIRCLE,
          25,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_NULL,
            new Color([137, 214, 171, 0.9]),
            1
          ),
          new Color([137, 214, 171, 0.5])
        );


        app.map.on("load", function(){
          app.map.graphics.enableMouseEvents();
          app.map.graphics.on("mouse-out", closeDialog);
        });

        //listen for when the onMouseOver event fires on the countiesGraphicsLayer
        //when fired, create a new graphic with the geometry from the event.graphic and add it to the maps graphics layer
        featureLayer.on("mouse-over", function(evt){
         var t = "<b>${SITENAME}</b><hr><b>Region: </b>${REGION}<br>";
          var content = esriLang.substitute(evt.graphic.attributes,t);
          var highlightGraphic = new Graphic(evt.graphic.geometry,point);
          app.map.graphics.add(highlightGraphic);

          dialog.setContent(content);

          domStyle.set(dialog.domNode, "opacity", 0.85);
          dijitPopup.open({
            popup: dialog,
            x: evt.pageX,
            y: evt.pageY
          });
        });


        // selection symbol used to draw the selected census block points within the buffer polygon
        var symbol2 = new SimpleMarkerSymbol(
          SimpleMarkerSymbol.STYLE_CIRCLE,
          12,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_NULL,
            new Color([247, 34, 101, 0.9]),
            1
          ),
          new Color([207, 34, 171, 0.5])
        );
        featureLayer.setSelectionSymbol(symbol2);

        // change cursor to indicate features are click-able
        featureLayer.on("mouse-over", function () {
            app.map.setMapCursor("pointer");
        });

        featureLayer.on("mouse-out", function () {
            app.map.setMapCursor("default");
        });

        // Add the Feature Layer To Map
        app.map.addLayer(featureLayer);


        // geometry service that will be used to perform the buffer
        var geometryService = new GeometryService("https://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

        //when the map is clicked create a buffer around the click point of the specified distance.
        app.map.on("click", function(evt){
          //define input buffer parameters
          var params = new BufferParameters();
          params.geometries  = [ evt.mapPoint ];
          params.distances = [ 50 ];
          params.unit = GeometryService.UNIT_STATUTE_MILE;

          geometryService.buffer(params);
        });

        geometryService.on("buffer-complete", function(result){
          app.map.graphics.clear();
          // draw the buffer geometry on the map as a map graphic
          var symbol2 = new SimpleFillSymbol(
            SimpleFillSymbol.STYLE_NULL,
            new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_SOLID,
              new Color([105,105,105]),
              2
            ),new Color([255,255,0,0.25])
          );
          var bufferGeometry = result.geometries[0]
          var graphic = new Graphic(bufferGeometry, symbol2);
          app.map.graphics.add(graphic);


 //Select features within the buffered polygon. To do so we'll create a query to use the buffer graphic
          //as the selection geometry.
          var query = new Query();
          query.geometry = bufferGeometry;
   // Select the Points within the Buffer and show them
          featureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function(results){
          });
          // Query for the records with the given object IDs and populate the grid
          featureLayer.queryFeatures(query, function (featureSet) {
            updateGrid(featureSet);
          });
      });



   } // End Function BufferTool

      function closeDialog() {
          app.map.graphics.clear();
          dijitPopup.close(dialog);
        }

      function updateGrid(featureSet) {
        var data = arrayUtils.map(featureSet.features, function (entry, i) {
          return {
            NAME: entry.attributes.SITENAME,
            REGION: entry.attributes.REGION,
            WATERBODY: entry.attributes.WATERBODY,
            TYPE: entry.attributes.TYPE,
            ACCESSAREA: entry.attributes.ACCESSAREA,
            LOCATION: entry.attributes.LOCATION
          };
        });
        grid.store.setData(data);
        grid.refresh();
      }

    // markerSymbol is used for point and multipoint, see http://raphaeljs.com/icons/#talkq for more examples
        var markerSymbol = new SimpleMarkerSymbol();
        markerSymbol.setPath("M16,4.938c-7.732,0-14,4.701-14,10.5c0,1.981,0.741,3.833,2.016,5.414L2,25.272l5.613-1.44c2.339,1.316,5.237,2.106,8.387,2.106c7.732,0,14-4.701,14-10.5S23.732,4.938,16,4.938zM16.868,21.375h-1.969v-1.889h1.969V21.375zM16.772,18.094h-1.777l-0.176-8.083h2.113L16.772,18.094z");
        markerSymbol.setColor(new Color("#00FFFF"));
    // lineSymbol used for freehand polyline, polyline and line.
        var lineSymbol = new CartographicLineSymbol(
          CartographicLineSymbol.STYLE_SOLID,
          new Color([55,77,173,.75]), 1.5,
          CartographicLineSymbol.CAP_ROUND,
          CartographicLineSymbol.JOIN_MITER, 5
        );
    // fill symbol used for extent, polygon and freehand polygon, use a picture fill symbol
    // the images folder contains additional fill images, other options: sand.png, swamp.png or stiple.png
 var fillSymbol = new SimpleFillSymbol(
          SimpleFillSymbol.STYLE_SOLID,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_SOLID,
            new Color([55,77,173,0.35]),
            2
          ),
          new Color([125,125,125,0.35])
        );


    // function toolbar
        function initToolbar() {
   alert("In initToolbar");

          tb = new Draw(map);
          tb.on("draw-end", addGraphic);
     // event delegation so a click handler is not
     // needed for each individual button
          on(dom.byId("info"), "click", function(evt) {
            if ( evt.target.id === "info" ) {
              return;
            }
            var tool = evt.target.id.toLowerCase();
            map.disableMapNavigation();
            tb.activate(tool);
          });
        }
    // add graphic
        function addGraphic(evt) {
          //deactivate the toolbar and clear existing graphics
          tb.deactivate();
          app.map.enableMapNavigation();

          // figure out which symbol to use
          var symbol;
          if ( evt.geometry.type === "point" || evt.geometry.type === "multipoint") {
            symbol = markerSymbol;
          } else if ( evt.geometry.type === "line" || evt.geometry.type === "polyline") {
            symbol = lineSymbol;
          }
          else {
            symbol = fillSymbol;
          }

          app.map.graphics.add(new Graphic(evt.geometry, symbol));
        }
0 Kudos
39 Replies
jaykapalczynski
Honored Contributor
Any thoughts on this...I tried to limited the amount of code I put in there...
I can run each button individually with a browser refresh in between...I just cant seem to figure out how to connect and disconnect properly to the IDENTIFY and BUFFER and visa versa
Really appreciate your help
0 Kudos
KenBuja
MVP Esteemed Contributor
This code has possible map click actions, with a button to activate each one.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples
      on iOS devices-->
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Explicitly Create Map Service Layer List</title>

    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">

    <script src="http://js.arcgis.com/3.8/"></script>

    <script>
        var layer, map, visible = [];
        var action1, action2;

        require(["esri/map", "dijit/registry", "dojo/parser",
            "dijit/form/Button", "dojo/domReady!"],
            function (Map, registry, parser) {
                parser.parse();

                map = new Map("map", {
                    basemap: "topo",
                    center: [-122.45, 37.75], // long, lat
                    zoom: 13,
                    sliderStyle: "small"
                });

                registry.byId('btnAction1').on("click", function () {
                    if (action2 != undefined) {
                        action2.remove();
                    }

                    if (action1 == undefined) {
                        action1 = map.on("click", function (evt) {
                            alert("Action 1 started");
                        });
                    }
                });

                registry.byId('btnAction2').on("click", function () {
                    if (action1 != undefined) {
                        action1.remove();
                    }
                    if (action2 == undefined) {
                        action2 = map.on("click", function (evt) {
                            alert("Action 2 started");
                        });
                    }
                });
            });


    </script>
</head>
<body class="claro">
    <button id="btnAction1" data-dojo-type="dijit/form/Button">Action 1</button>
    <button id="btnAction2" data-dojo-type="dijit/form/Button">Action 2</button>

    <div id="map" class="claro" style="width:600px; height:400px; border:1px solid #000;"></div>
</body>
</html>
0 Kudos
jaykapalczynski
Honored Contributor
Thanks a bunch....I have one more question....I took the JS code and placed it in a .JS page and referenced it in the HTML like this

<script src="js/warbler4.js"></script>

Per your example I placed this code in the .js page thats in the js folder

Everything else is the same and it no longer works...I place the JS code back in the HTML page and it works....I know the JS file is in the correct location and the code is in it....it should work fine....cleared my cache...

Puzzling.....thoughts...

HTML CODE:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples
      on iOS devices-->
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Explicitly Create Map Service Layer List</title>

    <link rel="stylesheet" href="https://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.8/js/esri/css/esri.css">

    <script src="js/warbler4.js"></script>

    <script src="https://js.arcgis.com/3.8/"></script>

</head>
<body class="claro">
    <button id="btnAction1" data-dojo-type="dijit/form/Button">Action 1</button>
    <button id="btnAction2" data-dojo-type="dijit/form/Button">Action 2</button>

    <div id="map" class="claro" style="width:600px; height:400px; border:1px solid #000;"></div>
</body>
</html>



THIS IS IN THE warbler4.js file which is in the JS folder

        var layer, map, visible = [];
        var action1, action2;

        require(["esri/map", "dijit/registry", "dojo/parser",
            "dijit/form/Button", "dojo/domReady!"],
            function (Map, registry, parser) {
                parser.parse();

                map = new Map("map", {
                    basemap: "topo",
                    center: [-122.45, 37.75], // long, lat
                    zoom: 13,
                    sliderStyle: "small"
                });

                registry.byId('btnAction1').on("click", function () {
                    if (action2 != undefined) {
                        action2.remove();
                    }
                    action1 = map.on("click", function (evt) {
                        alert("Action 1 started");
                    });
                });

                registry.byId('btnAction2').on("click", function () {
                    if (action1 != undefined) {
                        action1.remove();
                    }
                    action2 = map.on("click", function (evt) {
                        alert("Action 2 started");
                    });
                });
            });
0 Kudos
KenBuja
MVP Esteemed Contributor
IT's probably because you have that script loading before the Esri API script

This is what works for me. It turns out my original script didn't work with multiple switches between the buttons, so that's been fixed.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples
      on iOS devices-->
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Explicitly Create Map Service Layer List</title>

    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">

    <script src="http://js.arcgis.com/3.8/"></script>

    <script src="js/warbler4.js"></script>  

</head>
<body class="claro">
    <button id="btnAction1" data-dojo-type="dijit/form/Button">Action 1</button>
    <button id="btnAction2" data-dojo-type="dijit/form/Button">Action 2</button>

    <div id="map" class="claro" style="width:600px; height:400px; border:1px solid #000;"></div>
</body>
</html>


js/warbler4.js code

var layer, map, visible = [];
var action1, action2;

require(["esri/map", "dijit/registry", "dojo/parser", "dojo/on",
    "dijit/form/Button", "dojo/domReady!"],
    function (Map, registry, parser, on) {
        parser.parse();

        map = new Map("map", {
            basemap: "topo",
            center: [-122.45, 37.75], // long, lat
            zoom: 13,
            sliderStyle: "small"
        });

        registry.byId('btnAction1').on("click", function () {
            if (action2 != undefined) {
                action2.pause();
            }

            if (action1 == undefined) {
                action1 = on.pausable(map, "click", function (evt) {
                    alert("Action 1!");
                });
            }
            else {
                action1.resume();
            }
        });

        registry.byId('btnAction2').on("click", function () {
            if (action1 != undefined) {
                action1.pause();
            }
            if (action2 == undefined) {
                action2 = on.pausable(map, "click", function (evt) {
                    alert("Action 2!");
                });
            }
            else {
                action2.resume();
            }
        });
    });
0 Kudos
jaykapalczynski
Honored Contributor
I copied your last example verbatim (One in the html and the other in the JS) and it does not draw the map...only the two buttons show up and the border of the Map...
hmmmm


EDIT !!!! oops I needed it to be HTTPS ... Be right back testing
0 Kudos
jaykapalczynski
Honored Contributor
Thanks for your help its greatly appreciated.
Have another issue maybe you can help with

Why are the buttons deactivated in this

http://jsfiddle.net/hzNmf/6/
0 Kudos
JonathanUihlein
Esri Regular Contributor
I modified your sample a bit to console.log("clicked") when a particular button is pressed.

http://jsfiddle.net/hzNmf/8/
0 Kudos
jaykapalczynski
Honored Contributor
Thanks jon.uihlein  think I have it working...have to give props to above first to kenbuja for sticking with me through this....BOTH of your help is greatly appreciated.

THANKS
0 Kudos
jaykapalczynski
Honored Contributor
Ran into one more issue..... I can still call the buffer with the old code but for some reason the new on(dojo.byID example is blowing up when I try and turn the geometry service on in the buffer code.
THIS DOES NOT happen when I use the old code

I guess the question is how do I properly call the buffer code from the EXAMPLE 2 below and then properly disconnect the Click in the Buffer code so it does not continue to fire on map click.....you example worked great for an Alert but I dont know where to call the Buffer code...I even tried to copy all the code into the function.

The FIRST example works fine....BUT does not allow me to use other tools because I need to disconnect from the Click in the buffer

Do I have something wrong in the EXAMPLE 2 below...

EXAMPLE 1 OLD CODE
    on(dom.byId("BUFFER"), "click", function () {
  dijit.byId("FirstPane").set('open',false); //Close
  BufferCall = connect.connect(app.map, "onClick", BufferTool(app.map))
    })


I tried this from the above example

EXAMPLE 2 NEW CODE
 on(dojo.byId('btnAction2'), "click", function () {
         if (action1 != undefined) {
             action1.pause();
         }
         if (action2 == undefined) {
      action2 = on.pausable(app.map, "click", function(evt) {
                 BufferTool();
                 //alert("Action 2!");
             });
         }
         else {
             action2.resume();
         }
    });



This is the Buffer Code being called from the above examples....

In example 2 above it gets to the Alert("8"); but not the Alert("8");

 function BufferTool(map){

        dialog = new TooltipDialog({
          id: "tooltipDialog",
          style: "position: absolute; width: 100px; font: normal normal normal 10pt Helvetica;z-index:100"
        });
        dialog.startup();

       // selection symbol used to draw the selected census block points within the buffer polygon
        var point = new SimpleMarkerSymbol(
          SimpleMarkerSymbol.STYLE_CIRCLE,
          25,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_NULL,
            new Color([137, 214, 171, 0.9]),
            1
          ),
          new Color([137, 214, 171, 0.5])
        );

        app.map.on("load", function(){
          app.map.graphics.enableMouseEvents();
          app.map.graphics.on("mouse-out", closeDialog);
        });

        //listen for when the onMouseOver event fires on the countiesGraphicsLayer
        //when fired, create a new graphic with the geometry from the event.graphic and add it to the maps graphics layer
        featureLayer.on("mouse-over", function(evt){
         var t = "<b>${SITENAME}</b><hr><b>Region: </b>${REGION}<br>";
          var content = esriLang.substitute(evt.graphic.attributes,t);
          var highlightGraphic = new Graphic(evt.graphic.geometry,point);
          app.map.graphics.add(highlightGraphic);

          dialog.setContent(content);

          domStyle.set(dialog.domNode, "opacity", 0.85);
          dijitPopup.open({
            popup: dialog,
            x: evt.pageX,
            y: evt.pageY
          });
        });

        // selection symbol used to draw the selected census block points within the buffer polygon
        var symbol2 = new SimpleMarkerSymbol(
          SimpleMarkerSymbol.STYLE_CIRCLE,
          12,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_NULL,
            new Color([247, 34, 101, 0.9]),
            1
          ),
          new Color([207, 34, 171, 0.5])
        );
        featureLayer.setSelectionSymbol(symbol2);

        // change cursor to indicate features are click-able
        featureLayer.on("mouse-over", function () {
            app.map.setMapCursor("pointer");
        });

        featureLayer.on("mouse-out", function () {
            app.map.setMapCursor("default");
        });

        // Add the Feature Layer To Map
        app.map.addLayer(featureLayer);


        // geometry service that will be used to perform the buffer
        var geometryService = new GeometryService("https://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

  BufferClick = app.map.on("click", function(evt){
          //define input buffer parameters
          var params = new BufferParameters();
          params.geometries  = [ evt.mapPoint ];
          params.distances = [ 10 ];
          params.unit = GeometryService.UNIT_STATUTE_MILE;
          geometryService.buffer(params);
        });

alert("Hey 8");

        geometryService.on("buffer-complete", function(result){
          app.map.graphics.clear();
          // draw the buffer geometry on the map as a map graphic
          var symbol2 = new SimpleFillSymbol(
            SimpleFillSymbol.STYLE_NULL,
            new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_SOLID,
              new Color([105,105,105]),
              2
            ),new Color([255,255,0,0.25])
          );
          var bufferGeometry = result.geometries[0]
          var graphic = new Graphic(bufferGeometry, symbol2);
          app.map.graphics.add(graphic);

alert("Hey 9");

 //Select features within the buffered polygon. To do so we'll create a query to use the buffer graphic
          //as the selection geometry.
          var query = new Query();
          query.geometry = bufferGeometry;
   // Select the Points within the Buffer and show them
          featureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function(results){
          });
          // Query for the records with the given object IDs and populate the grid
          featureLayer.queryFeatures(query, function (featureSet) {
            updateGrid(featureSet);
          });
      });

 } // End Function BufferTool
0 Kudos
KenBuja
MVP Esteemed Contributor
Two things.

I'm surprised it's not complaining about the fact that you're calling BufferTool function like this

 BufferTool();


with the function requiring the variable "map" to be passed into it.

Why are you adding in another map click listener with BufferClick?

     BufferClick = app.map.on("click", function(evt){           //define input buffer parameters           var params = new BufferParameters();           params.geometries  = [ evt.mapPoint ];           params.distances = [ 10 ];           params.unit = GeometryService.UNIT_STATUTE_MILE;           geometryService.buffer(params);         });

Why not set these parameters where you are initializing the event listener action2?
0 Kudos