[GIS] Using the jQuery UI Slider to control layer opacity in OpenLayers

jqueryopenlayers-2

Added some bounty so more people take a look at my question. Thank you.

I have been trying to utilize the jQuery UI Slider to control layer opacity in OpenLayers but I have an issue when trying to set the "value" option to anything other than the "max" value.

What I would like to see is the setOpacity method change my layer's opacity to 20% onload. However, the slider is shown in the correct position but the layer displays the "max" value of opacity (100%/opaque). Currently, a slide event triggers a change in opacity. I need to force the opacity of my WMS layers to be that of the manually set "value" options when the page loads.

Removed the any unnecessary code.
One slider shown below.
Your help is much appreciated!

<body onload="init()">
  <script type="text/javascript">
  $(document).ready(function(){
  $(function() {
      $( "#slider1" ).slider({
      range: "min",
      min: 0,
      value: 20,
      slide: function(e, ui) {
          hii_1.setOpacity(ui.value / 100);
          $( "#amount1" ).val( ui.value );
          }
      });
      $("#amount1" ).val($( "#slider1" ).slider( "value" ) );
  });
  });
  </script>
</body>

Best Answer

You have two options:

  1. hook into the create event to adjust layer opacity as sliders are created
  2. provide a global cfg array so that layers are already init'ed to same value as the sliders

The first solution is simple, just provide a create: function(event, ui) { ... } as an init option to the slider like the following:

$( "#slider1" ).slider({
   [...]
   create: function(event, ui) { ... }
   [...]
});

The second solution is even simpler and will ensure that the user always sees the layers at the right opacity. In the first solution there is a chance (albeit small) that the layers appear for a short time at 100% opacity until the sliders are created.

Define a global array like the following:

var opacities=[10, 20, 20];

in the OL init code set the opacity at layer creation time:

hii_1 = new OpenLayers.Layer.MapServer("Land Cover","../../cgi-bin/mapserv.exe",{
        map:'C:/ms4w/Apache/htdocs/hii/hii_landcover.map'},{
        isBaseLayer:false,
        transparent:true,
        format:"image/png",
        alpha:true
        });

hii_1.setOpacity(opacities[0] / 100);

and then do the same when creating the sliders:

$( "#slider1" ).slider({
      range: "min",
      min: 0,
      value: opacities[0],
      slide: function(e, ui) {
          hii_1.setOpacity(ui.value / 100);
          $( "#amount1" ).val( ui.value );
          }
      });

P.S.: code refactoring so that layer cfg is moved completely into the opacities array (which should be renamed at this point) and code duplication is reduced is left as an exercise to the reader.