How to hide infoWindow while using measure tool?

1769
7
Jump to solution
03-01-2013 11:45 AM
AlexGilvarry
New Contributor II
In my Javascript API Web application I'm using the infoWindow to query a parcel layer and display display information in a popup when I click the parcel. I've set this functionality to turn on and off depending on if the parcel is visible, and I control the visibility of my different layers with check boxes in a legend.

Every time the parcel layer is checked on of off it calls the clickConnect function with a value of true or false. Depending on this, click connect will call the executeIdentifyTask function, which query's the parcel layer, when clicked, and displays the info in a popup. This works great unless I try to use the esri.dijit.Measurement tool while the parcel layer is turned on. In which case i still get a pop up every time I click, which gets in the way of me measuring parcels.

Is there a way that I could turn the popup/query functionality off while I'm using the measure tool and the parcel layer is turned on? I'm a bit of a beginner at using javascript/dojo so I'm not sure how to do this.
 
Any help would be greatly appreciated! I hope I was clear in my explanation, if not let me know!

Javascript from my map app relevant to the question:

      var app = {};       app.map = null;         var legendLayers = [];       var clickHandler;        function init() {        //add popup         var popup = new esri.dijit.Popup({           fillSymbol: new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]))         }, dojo.create("div"));   //add geometry service         esri.config.defaults.geometryService = new esri.tasks.GeometryService("http://server/rest/services/Utilities/Geometry/GeometryServer");   //initalize map         app.map = new esri.Map("map", {           basemap : "streets",           center : [-111.924531, 40.611871],           zoom : 13,           infoWindow: popup         });         //add  parcel layer          var parcels = new esri.layers.ArcGISDynamicMapServiceLayer("http://server/arcgis/rest/services/Parcels_UT/MapServer", {           id : 'parcels',           visible : false         });         legendLayers.push({           layer : parcels,           title : 'Parcels'         });   //add parcel query data   var content = "<b>Address</b>: ${ADDR}" + "<br /><b>Owner Name</b>: ${OWNER}" + "<br /><b>Parcel ID</b>: ${APN}" + "<br /><b>City</b>: ${CITY}" + "<br /><b>Acres</b>: ${TOTAL_ACRE}" + " <br /><a href='${COUNTY_LIN}'>County Assessor Site</a>"      var popUpTemplate = new esri.InfoTemplate("Parcel", content);         //add paercel layer as feature layer         var featureLayer = new esri.layers.FeatureLayer("http://server/arcgis/rest/services/Parcels_UT/MapServer/0",{           mode: esri.layers.FeatureLayer.MODE_SELECTION,           outFields: ["*"],           infoTemplate:popUpTemplate         });          //create legend         dojo.connect(app.map, 'onLayersAddResult', function(results) {           var legend = new esri.dijit.Legend({             map : app.map,             layerInfos : legendLayers           }, "legendDiv");           legend.startup();         });         app.map.addLayers([parcels]);          dojo.connect(app.map, 'onLayersAddResult', function(results) {            //add legend check boxes           dojo.forEach(legendLayers, function(layer) {             var layerName = layer.title;             var checkBox = new dijit.form.CheckBox({               name : "checkBox" + layer.layer.id,               value : layer.layer.id,               checked : layer.layer.visible,               onChange : function(evt) {                 var clayer = app.map.getLayer(this.value);                 clayer.setVisibility(!clayer.visible);                 this.checked = clayer.visible;                                                  //toggle the feature layer with the parcel layer                 if (this.value ==="parcels" && this.checked === true){                  clickConnect(true);                  console.log("parcels");                 } else if (this.value ==="parcels"){                  clickConnect(false);                  console.log("noParcels");                 }                                }             });              //add the check box and label to the table of contnents             dojo.place(checkBox.domNode, dojo.byId("toggle"), "after");             var checkLabel = dojo.create('label', {               'for' : checkBox.name,               innerHTML : layerName             }, checkBox.domNode, "after");             dojo.place("<br />", checkLabel, "after");           });         });                    dojo.connect(app.map, 'onLoad', function(map) {           initToolbar(app.map);         });                   function executeIdentifyTask(evt) {       var query = new esri.tasks.Query();           query.geometry = pointToExtent(app.map,evt.mapPoint,10);           var deferred = featureLayer.selectFeatures(query,esri.layers.FeatureLayer.SELECTION_NEW);           app.map.infoWindow.setFeatures([deferred]);           app.map.infoWindow.show(evt.mapPoint);          }                   function clickConnect(connect){       if(connect){         //perform the identify task on click          clickHandler = dojo.connect(app.map, "onClick", executeIdentifyTask);       }else{         //disconnect the click handler          dojo.disconnect(clickHandler);         clickHandler = null;       }                }              }        function initToolbar(mymap) {         //define a new line symbol and point symbol to use for measure tools         var pms = new esri.symbol.PictureMarkerSymbol("images/flag.png", 24, 24);         pms.setOffset(9, 11);         var sls = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DOT, new dojo.Color([255, 0, 0, .55]), 4);         var measurement = new esri.dijit.Measurement({           map : mymap,           lineSymbol : sls,           pointSymbol : pms         }, dojo.byId('measurementDiv'));         measurement.startup();         measurement.setTool("area", false);        }              function pointToExtent(map, point, toleranceInPixel) {        var pixelWidth = map.extent.getWidth() / map.width;        var toleraceInMapCoords = toleranceInPixel * pixelWidth;        return new esri.geometry.Extent( point.x - toleraceInMapCoords,                     point.y - toleraceInMapCoords,                     point.x + toleraceInMapCoords,                     point.y + toleraceInMapCoords,                     map.spatialReference );                                  }              dojo.ready(init);
0 Kudos
1 Solution

Accepted Solutions
JianHuang
Occasional Contributor III
Try this:

dojo.connect(measurement.area, "onClick", function(){      if (this.checked) {        console.log("I'm checked");        dojo.disconnect(yourClickHandler);      }         });

View solution in original post

0 Kudos
7 Replies
JianHuang
Occasional Contributor III
Try this:

dojo.connect(measurement.area, "onClick", function(){      if (this.checked) {        console.log("I'm checked");        dojo.disconnect(yourClickHandler);      }         });
0 Kudos
AlexGilvarry
New Contributor II
This is great, thanks! but how would I go about turning the popups back on when I'm finished using that tool? I tried messing with it   for a while to make that work, but I couldn't make anything work. Apparently dojo only registers the "onClick" when you're turning the measurement tool on, not when you click to turn it back off.
0 Kudos
AlexGilvarry
New Contributor II
Thank you! After messing around with this for a little bit everything made sense and I got it working.
0 Kudos
MichaelKnapp
Occasional Contributor
Hi There -

Luckily I saw this post because I had the exact same issue... I just wanted to clarify that the "dojo.connect(measurement.area, ..." solution mentioned by Jian above works when placed inside the "dojo.connect(map,....." command.

For example......

dojo.connect(map, "onLoad", function(map){
          var measurement = new esri.dijit.Measurement({map: map}, dojo.byId('measurementDiv'));
          measurement.startup();
          measurement.hideTool("area");

          dojo.connect(measurement.distance, "onClick", function(){
     if (this.checked) {
       console.log("Distance Tool was activated");
              map.graphics.disableMouseEvents();
     }
           });
          dojo.connect(measurement, "onMeasureEnd", function(activeTool,geometry){
                    this.setTool(activeTool, false);
                    setTimeout(function() { measurement.clearResult(); }, 3000);
                    map.graphics.enableMouseEvents();
          });
   });


Thanks.

M. Knapp
0 Kudos
KevinMacLeod1
Occasional Contributor III
Thank you both, I see what these do conceptually. Unfortunately I tried both ways, neither work in 3.3.

So, for my site I'd used sample code here to use Identify Task on my layer where it loops through and identifies everything. http://jsfiddle.net/URpaW/ Also I called my measurement object 'measurement' as you all did above.

It pops up always, after clicking measurement tools.

First I tried M. Knapp's method of disabling mouse events. While console messages fired, it didn't work. I checked the API Reference and noticed there isn't even a enableMouseEvents or disableMouseEvents  in map.graphics! Or perhaps it is there but I did not see it. The API page needs a more robust Search.

I then tried Jian's idea -- disabling the handler (doIdentify  for onClick of map  which stores the Identify logic). Also added connect to put it back after Measurement was stopped.

I got a message saying Dojo.js did not support removing the object. Console messages again fired successfully but this did not work either. 😕

Thoughts?

I will continue working on this and update...
0 Kudos
KevinMacLeod1
Occasional Contributor III
I tried both ways and they did not work, but I figured it out with a way similar to  Jian's ...

Here:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9" />
        <!-- // 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"/>
        <!-- // include a title for the window tab name -->
    <title>Multiple Service Layer Identify Popup InfoWindow</title>
        <!-- // define the location of the JavaScript API version 3.1 -->
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.1/js/dojo/dijit/themes/soria/soria.css">
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.1/js/esri/dijit/css/Popup.css">    

<style type="text/css">
      html,
      body { height: 100%; width: 100%; margin: 0; padding: 0; }

</style>
    <script type="text/javascript">        
    var djConfig = { parseOnLoad: true };
    </script>   
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=3.1"></script>
    <script type="text/javascript" language="Javascript">
        dojo.require("esri.map");
        dojo.require("esri.dijit.Measurement");
        dojo.require("dijit.layout.BorderContainer");
        dojo.require("dijit.layout.ContentPane");
        dojo.require("esri.dijit.Popup");
        dojo.require("dojo.DeferredList");

        dojo.require("esri.arcgis.utils");        
        dojo.require("esri.layers.FeatureLayer");


    var identifyParams;
    var tasks;
    var clickPoint;
 var connection;
 var checked;
var map;
    function init() {

        var popup = new esri.dijit.Popup({ fillSymbol: new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0.25]))}, dojo.create("div"));

        var initialExtent = new esri.geometry.Extent({"xmin":-9549173.347091435,"ymin":4614123.468713058,"xmax":-9546388.17287322,"ymax":4615432.452822477,"spatialReference":{"wkid":102100}});
        map = new esri.Map("map", {  extent: initialExtent, infoWindow: popup }); dojo.place(popup.domNode, map.root);

          dojo.connect(map,'onLoad',function(){
              //setup generic identify parameters 
              identifyParams = new esri.tasks.IdentifyParameters();
              identifyParams.tolerance = 10;
              identifyParams.returnGeometry = true;
              identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;

            
    dojo.connect(map,'onClick',doIdentify);
    
            });

         var basemap = new esri.layers.ArcGISTiledMapServiceLayer("http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer");                
        map.addLayer(basemap);

        var dynlayer1 = new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyFeedSample/MapServer",{opacity:.50});
        var dynlayer2 = new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyHazardsandRisks/MapServer",{opacity:.50});
        var dynlayer3 = new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyOperationalLayers/MapServer");
       var measurement = new esri.dijit.Measurement({
            map: map
          }, dojo.byId('measurementDiv'));
          measurement.startup();
   
   
   dojo.connect(measurement.area, "onClick", function(){
     //change the value as you click on the tool
  if (this.checked) {
      checked=true;
     } 
else  
 checked=false;
  
   });
   
   
    dojo.connect(measurement.distance, "onClick", function(){
     
  if (this.checked) {
      checked=true;
     } 
else  
 checked=false;
  
   });
      

   
   
       dojo.connect(map,'onLayersAddResult', setupIdentify);
       map.addLayers([dynlayer3,dynlayer2,dynlayer1]);


  }
  function setupIdentify(results){
    //loop through operational layers and add identify task for each. 
    tasks = dojo.map(results,function(result){
        return new esri.tasks.IdentifyTask(result.layer.url);
    });


  }
  function doIdentify(evt){
  // only do the identify when the tool is not used
  if (checked!=true)
      {
   map.infoWindow.hide();
        clickPoint = evt.mapPoint;

        identifyParams.geometry = evt.mapPoint;
        identifyParams.mapExtent = map.extent;
        identifyParams.width  = map.width;
        identifyParams.height = map.height;

      var deferreds = dojo.map(tasks,function(task){
        return task.execute(identifyParams);
      });
      var dlist = new dojo.DeferredList(deferreds);
      dlist.then(handleQueryResults);
}
  }
  function handleQueryResults(results){

    var features = [];
    dojo.forEach(results,function(result){
      // for a simplified test let's just display all the attributes in the popup 
      if(result[1].length > 0){
        dojo.forEach(result[1],function(r){
          var feature = r.feature;
          console.log(feature);
          feature.attributes.layerName =r.layerName;

           var infoTemplate = new esri.InfoTemplate('Attributes', "${*}");
          feature.setInfoTemplate(infoTemplate);
          features.push(feature);

        });
      }

    });
    map.infoWindow.setFeatures(features);
    map.infoWindow.show(clickPoint);

  }
        dojo.addOnLoad(init);
    </script>
</head>
<body class="soria">
    <div id="mainWindow" dojotype="dijit.layout.BorderContainer" design="headline" gutters="false" style="width:100%; height:100%;">
      <div id="map" class="shadow" dojotype="dijit.layout.ContentPane" region="center" >
            <div style="position:absolute; right:20px; top:10px; z-Index:999;">
          <div id="titlePane" data-dojo-type="dijit.TitlePane" data-dojo-props="title:'Measurement', closable:'false', open:'false'">
            <div id="measurementDiv"></div>
            <span style="font-size:smaller;padding:5px 5px;">Press <b>CTRL</b> to enable snapping.</span>
          </div>
        </div>
      </div>      


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


Thanks to Rui from ESRI Support for help with this also.

Note that I had to have measurement be at the bottom of our production code. I've seen this before. Weird errors can happen when the measurement dijit instantatiation code for the measurement object is above code for certain other widgets. Hope this gets fixed eventually as it is a confusing issue as the errors don't really lead you to this conclusion and it is not documented as something that needs to be done in the API.
0 Kudos
MirceaMaierean
New Contributor III
I'm in the same situation and I want to be able to measure on top of a feature layer. Anyone knows how would you be able to do this on AMD?

 var measurement;
     
        ready(function(){

            parser.parse();

  //Create a map 
  var map = new Map("map", {
   center: [-112.0000, 34.0000],
         zoom: 7,
         basemap: "topo"
   });
  
   measurement = new Measurement({
       map: map
       }, dom.byId("measureDiv"));
       measurement.startup();
      
  //set the popup's popupWindow property to false. This prevents the popup from displaying
  map.infoWindow.set("popupWindow", false);
  initializeSidebar(map);
  
                // Create info Template
  var template = new InfoTemplate();
  template.setContent("<b>Counties info:</b><br/>" +
       "County Name: <b>${NAME}</b><br/>"+
       "Reimbursment 1: <b>${Reim1}</b><br/>" +
       "Reimbursment 2: <b>${Reim2}</b><br/>" +
       "Reimbursment 3: <b>${Reim3}</b><br/>" + 
       "Reimbursment 4: <b>${Reim4}</b><br/>" +
       "<hr>"+
       "<b>Game Management Units Info:</b><br/>" +
       "GMU: <b>${GMU}</b><br/>"+
       "Region Name: <b>${REG_NAME}</b><br/>" +
       "Landown: <b>${LANDOWN}</b><br/>" +
       "Hunt: <b>${HUNT}</b><br/>");
       
  //add features to map
  var Outside = new FeatureLayer("URL",{
    mode: FeatureLayer.MODE_ONDEMAND,
    infoTemplate: template,
    outFields: ["NAME"]
    }); 
  
  var Counties = new FeatureLayer("URL",{
    mode: FeatureLayer.MODE_ONDEMAND,
    infoTemplate: template,
    outFields: ["NAME", "Reim1", "Reim2", "Reim3", "Reim4"]
    }); 
      
       var GMUs = new FeatureLayer("URL", {
        mode: FeatureLayer.MODE_ONDEMAND,
        infoTemplate: template,
        outFields:["GMU", "REG_NAME", "LANDOWN", "HUNT"]
        });
      
       var Travel = new FeatureLayer("URL", {
        mode: FeatureLayer.MODE_ONDEMAND,
        outFields:["*"]
        });
      
      map.addLayers([Outside,Counties,GMUs,Travel]);
    
 });

            function initializeSidebar(map){
                var popup = map.infoWindow;

                //when the selection changes update the side panel to display the popup info for the 
                //currently selected feature. 
                connect.connect(popup, "onSelectionChange", function(){
                    displayPopupContent(popup.getSelectedFeature());
                });

                //when the selection is cleared remove the popup content from the side panel. 
                connect.connect(popup, "onClearFeatures", function(){
                    //dom.byId replaces dojo.byId
                    dom.byId("featureCount").innerHTML = "Click to select feature(s)";
                    //registry.byId replaces dijit.byId
                    registry.byId("leftPane").set("content", "");
                    domUtils.hide(dom.byId("pager"));
                });

                //When features are associated with the  map's info window update the sidebar with the new content. 
                connect.connect(popup, "onSetFeatures", function(){
                    displayPopupContent(popup.getSelectedFeature());
                    dom.byId("featureCount").innerHTML = popup.features.length + " feature(s) selected";

                    //enable navigation if more than one feature is selected 
                    popup.features.length > 1 ? domUtils.show(dom.byId("pager")) : domUtils.hide(dom.byId("pager"));
                });
            }
            
            function displayPopupContent(feature){
                if(feature){
                    var content = feature.getContent();
                    registry.byId("leftPane").set("content", content);
                }
            }
      
                on(dojo.byId("clearAll"), "click", clearmeas);
            function clearmeas(){
                measurement.clearResult();
            }
            
         });
            

   
</script>
</head>

<body class="claro">
<div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline',gutters:false" style="width:100%; height:100%;">
    <div data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="gutters:false" region="left" style="width: 20%;height:100%;">
        <div id="leftPane" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'"></div>
        <div id="header" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top'">
            <div id="featureCount" style="margin-bottom:5px;">Click on feature(s) to select</div>
            <!--<input type="text" id="capacity" value="4" />
            <input type="button" value="Get Details" onclick="executeQueryTask(dojo.byId('capacity').value);" />-->
            <div id="pager" style="display:none;"> 
                <a href='javascript:void(0);' id ="previous" class='nav' style="text-decoration: none;">
                    &lt; Prev
                </a>
                  
                <a href='javascript:void(0);' id="next" class='nav'  style="text-decoration: none;">
                    Next &gt;
                </a>
            </div>
        </div>
    </div>
    <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'">
     <div id="search"></div>
    <div id="HomeButton"></div>
    <div id="BasemapToggle"></div>
    <div style="position:absolute; right:20px; top:20px; z-Index:999;">
          <div id="titlePane" data-dojo-type="dijit.TitlePane" data-dojo-props="title:'Measurement Tool', open: false">
            <span style="font-size:smaller;padding: 20px;">Select the Area or Distance measurement</br> tool then click the map to start measuring.</br> Double click to finish measuring.</span>
            <div id="measureDiv"></div><hr><button id="clearAll" type="button">Clear Measure</button>
            </div>
</div>
</div>
</div>
</body>

</html> 


Updated with the code. Im new to javascript and new to code so Im still trying to figure this out. It took me a few weeks to get at this point and the Web app is almost done just need this to figure out. I tried adding another button that would disableMouseEvents but that didnt work out. I also looked at the measure widget options but couldnt figure those out.

Thanks in advance.
0 Kudos