[GIS] openlayers toggle visibility of layer

drupalopenlayers-2

EDIT: I have cross-posted this to Drupal Answers. I hope this isn't too much against the rules — I think the answer will be something to do with both Drupal and OpenLayers.
https://drupal.stackexchange.com/questions/50733/openlayers-toggle-visibility-of-layer

I'm using OpenLayers in Drupal and am stuck while trying to make a layer toggle on and off (as it does from the right-side layer switcher).

See this map.
http://dev.lambeth.coop/map

Click on food growing projects.

EDIT: I've changed the code to show the Drupal-specific elements.

(function ($) {
  Drupal.behaviors.openlayers_switcher = {
    attach: function(context, settings) {
      $(document).ready(function() {
        $('[id^=openlayers-switcher-block--]').click(function(e) {
          $(this).toggleClass('active');
          // 27 is the length of 'openlayers-switcher-block--'
          // layername is the string following that.
          var layername = e.target.id.substring(27);
          var ol = $('.openlayers-map').data('openlayers');
          var layers = ol.openlayers.getLayersByName(layername);

          // this doesn't work
          // if (layers[0].visibility) {
            // layers[0].setVisibility(false);
          // }
          // else {
            // layers[0].setVisibility(true);
          // }
        });
      });
    }
  }
}(jQuery));

When I try to toggle visibility – the visibility doesn't change.

EDIT: So it appears that the entire click function is being called twice.

I've tried putting these lines (in various combinations) at the beginning of the function, as these have been suggested in google searches for 'click events firing twice' etc.

$('[id^=openlayers-switcher-block--]').click(function(e) {
  e.preventDefault();
  e.stopPropagation();

… but these don't help – I still get the function called twice.

In any case, I'm new to openlayers and would be grateful for a way forward!

Thanks!

Best Answer

I cannot fully understand the code you have posted.

When using the library OpenLayers, the usual programming pattern - as seen in the examples available at OpenLayers web page - consists on creating an instance of OpenLayers.Map that is stored in a global variable, so it is available to every function.

Let us suppose that this variable is named map; then, you would get the layer whose visibility you want to toggle with a JavaScript code like this:

var layerName = 'food-growing-projects';
var layer = map.getLayersByName(layerName)[0];
layer.setVisibility(true);

I hope this helps.