openlayers bindTo事件不起作用

时间:2015-07-19 13:49:47

标签: openlayers

我遇到问题,切换复选框无效,控制台显示如下。  代码:

<!doctype html>
<head>
    <title> Me OpenStreetMap </title>
    <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
    <link rel="stylesheet" href="../assets/ol3/css/samples.css" type="text/css" />
</head>
<body>

    <div id="map"></div>
    <input type="checkbox" id="visible" checked />Toggle layer Visibility

<script src="../assets/ol3/js/ol.js"></script>
<script>
    var center = new ol.proj.transform([11.57,3.86], 'EPSG:4326','EPSG:3857');
    var view = new ol.View({
     zoom: 6,
     center: center
    });
    var layer = new ol.layer.Tile({
        source: new ol.source.OSM()
    });

    var map = new ol.Map({
        target: 'map',
        layers: [layer],
        view: view
    });

    // bind a checkbox with id 'visible' to a layer's visibility
    var visible = new ol.dom.Input(document.getElementById('visible'));  /* line 30 */
    visible.bindTo('checked', layer, 'visible');

</script>

</body>
</html>

显示地图,但复选框没有响应,控制台日志显示:

Uncaught TypeError: Cannot read property 'Input' of undefined
(anonymous function) @ events.html:30

我经历了这个但仍然没有得到它OpenLayers - Uncaught TypeError: Cannot read property 'div' of undefined

1 个答案:

答案 0 :(得分:5)

如果您想使用此功能,请确保您的库的版本低于3.5.0,因为版本3.5.0中已删除ol.dom.Inputhttps://github.com/openlayers/ol3/releases/tag/v3.5.0

  

已删除实验性ol.dom.Input组件。如果你需要   将dom Input元素的状态与ol.Object同步,   这可以使用侦听器来完成更改事件。对于   例如,您可以使用a绑定复选框类型输入的状态   图层的可见性如下:

var layer = new ol.layer.Tile();
var checkbox = document.querySelector('#checkbox');

checkbox.addEventListener('change', function() {
  var checked = this.checked;
  if (checked !== layer.getVisible()) {
    layer.setVisible(checked);
  }
});

layer.on('change:visible', function() {
  var visible = this.getVisible();
  if (visible !== checkbox.checked) {
    checkbox.checked = visible;
  }
});