[GIS] OpenLayers – Test Control To See If It Is Active

openlayers-2

I am trying to get the active state of an OpenLayers SelectFeature control. I create this control and add it to my map but I do NOT activate it yet. This part works fine. Here is the script to create the control and add it to the map:

var highlightControl = new OpenLayers.Control.SelectFeature(lyrstands, {
        hover: true,        
        highlightOnly: true,                
selectStyle: {
   fill: "#0000FF",
           strokeColor: "#0000FF",
           strokeWidth: 2,
   fillOpacity: 0.5
          }
    });


map.addControl(highlightControl);

Then I have a button that calls a function. Here is the code for the button:

new OpenLayers.Control.Button({title: "Select Polygon", trigger: HiLite})   

I know the button is calling the HiLite function because if I put a simple alert statement in the HiLite function (for example: alert("The Function Works");) it works correctly.

So what I am trying to do is check to see if highlightControl has been activated by testing the highlightControl.active value, if it is already activated the function should do nothing, but, if highlightControl is NOT activated it should activate it. Unfortunately, the function does not work. Here is the function I have written:

function HiLite(){
  if (highlightControl.active==false)       
          {highlightControl.activate();}
  else {}
   } 

If I write the function to simply activate the tool without the If Else stuff it works fine. But, for some reason when written as above I cannot get the status of the Active attribute. The OpenLayers documentations states that the Active attribute is a Boolean value and I assumed I could check the status using the highlightControl.active==false statement.

Why can I not get this function to work?

Best Answer

Maybe there is a problem with the visibility of your highlightControl variable. You could try to add an ID to your control, and than access it like this:

var highlightControl = new OpenLayers.Control.SelectFeature(lyrstands, {
    //add ID
    id: 'Mycontrol',
    hover: true,        
    highlightOnly: true,                
selectStyle: {
fill: "#0000FF",
       strokeColor: "#0000FF",
       strokeWidth: 2,
fillOpacity: 0.5
      }
});
//then do something like this
var control = map.getControlsBy("id", "Mycontrol")[0];
    if (!control.active) {
         control.activate();
     }

EDIT

This problem was solved thanks to SirijuS. Here is the code fix:

var highlightControl = new OpenLayers.Control.SelectFeature(lyrstands, {        
    id: 'ctrlHiLite',                
    hover: true,        
            highlightOnly: true,                     
    selectStyle: {
       fill: "#0000FF",
               strokeColor: "#0000FF",
               strokeWidth: 2,
       fillOpacity: 0.5
              }
        });

function HiLite() {

var control = map.getControlsBy("id", "ctrlHiLite")[0];
    if (!control.active) {
     control.activate();
 }
}