The bindTo
method is extremely powerful and makes many seemingly advanced tasks quite easy to accomplish. Let's set up an HTML checkbox element that we can use to control the visibility of a map layer.
Using the same sample file we started earlier in the chapter, add the following on a new line between
<div id="map">
and the<script>
tag:<input type="checkbox" id="visible" checked> Toggle Layer Visibility
This will add a new HTML element, a checkbox, to our web page and we will use this to turn our layer on and off.
Next, add the following two lines of code at the end of the script tag:
var visible = new ol.dom.Input(document.getElementById('visible')); visible.bindTo('checked', layer, 'visible');
This code creates a new instance of
ol.dom.Input
, an OpenLayers helper class that connects to our checkbox element. It then uses thebindTo()
method to observe changes in the checked attribute and send them to the layer, specifically to the visible property...