OpenLayers 3 Beginner’s Guide

Playing with various sources and layers together

Open sample in a new windows

<!doctype html>
<html>
  <head>
    <title>Playing with various sources and layers</title>
    <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
    <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
  </head>
  <body>
    <div id="map" class="map"></div>
    <script src="../assets/ol3/js/ol.js"></script>
    <script>

    var bingMapsAerial = new ol.layer.Tile({
      preload: Infinity,
      source: new ol.source.BingMaps({
        key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
        imagerySet: 'Aerial'
      })
    });

    bingMapsAerial.set('name', 'Bings Maps Aerial');

    var bingMapsRoad = new ol.layer.Tile({
      preload: Infinity,
      source: new ol.source.BingMaps({
        key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
        imagerySet: 'Road',
        culture: 'fr-FR'
      })
    });

    bingMapsRoad.set('name', 'Bings Maps Road');

    var mapQuestAerial = new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'sat'})
    });

    mapQuestAerial.set('name', 'MapQuest Open Aerial');

    var simpleWMS = new ol.layer.Image({
          opacity: 0.6,
      source: new ol.source.ImageWMS({
        url: 'http://demo.boundlessgeo.com/geoserver/wms',
        params: {
          'LAYERS': 'topp:states'
        },
        extent: [-13884991, -7455066, 2870341, 6338219]
      })
    });
    simpleWMS.set('name', 'USA layer from Geoserver WMS demo');

    var layers = [bingMapsAerial, bingMapsRoad, mapQuestAerial, simpleWMS];

    var map = new ol.Map({
      layers: layers,
      target: 'map',
      view: new ol.View({
        center: ol.proj.transform([-90, 40], 'EPSG:4326', 'EPSG:3857'),
        zoom: 3
      })
    });

    //Generate checkbox from layers array
    function generate_checkbox(id_checkbox, label_name, html_element) {
      var checkbox = document.createElement('input');
      checkbox.type = "checkbox";
      checkbox.id = id_checkbox;

      var label = document.createElement('label');
      label.htmlFor = id_checkbox;
      label.appendChild(document.createTextNode(label_name));
      html_element.appendChild(checkbox);
      html_element.appendChild(label);
    }

    // Loop from the end to get the top layer in first
    for (var i = layers.length - 1; i >= 0; i--) {
      var id = layers[i].get('id');
      var name = layers[i].get('name');
      generate_checkbox('layer_id_' + i, name, document.body);
      var visible = new ol.dom.Input(document.getElementById('layer_id_' + i));
      visible.bindTo('checked', layers[i], 'visible');
    }

    </script>
  </body>
</html>