cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <script src="https://api3.geo.admin.ch/loader.js"></script>

<div id="map" class="map"></div>

<div id="layers"></div>
<p>
  This examples displays all layers available as WMTS LV95 (<a href="https://epsg.io/2056" target="_blank">EPSG:2056</a>).<br>
  The WMTS tiles are reframed <em>on-the-fly</em> using <a href="http://mapproxy.org">MapProxy</a> and the NTv2 <a href="https://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/surve
y/lv95/lv03-lv95/chenyx06.html"> CHENyx06 triangular transformation network </a>.
  Hence the accuracy is well beyond the resolution of the displayed layers. Without this you would see in region like the south Ticino and the Poschiavo area, a shift up to 1.5 meters between the old and the new frame. See <a href="https://map.geo.admin.ch/?layers=ch.swisstopo.koordinatenaenderung&layers_opacity=0.75&lang=en" target="_blank">LV95 Coordinate changes</a> for some background informations.<br>
  Have a look at what <a href="//api3.geo.admin.ch/services/sdiservices.html#other-projections" target="_blank" >projections are available</a>.</p>
</p>
            
          
!
            
              body {
  padding: 0;
  margin: 0;
}

.map {
  height: 350px;
}
            
          
!
            
              // SERVICE_BASE_URL and WMTS_BASE_URL comes from a common pen https://codepen.io/geoadmin/pen/dMPJGy?editors=0010

// We create an ol.source.WMTS
var wmtsSource = function(layer, options) {
  var resolutions = options.resolutions ? options.resolutions : RESOLUTIONS;
  var tileGrid = new ol.tilegrid.WMTS({
    origin: [extent[0], extent[3]],
    resolutions: resolutions,
    matrixIds: matrixIds
  });
  var extension = options.format || 'png';
  var timestamp = options.timestamp || options['timestamps'][0];
  return new ol.source.WMTS(({
    attributions: [new ol.Attribution({
      html: '<a target="new" href="https://www.swisstopo.admin.ch/' +
      'internet/swisstopo/en/home.html">swisstopo</a>'
    })],
    url: (WMTS_BASE_URL + '/1.0.0/{Layer}/default/' +
          timestamp + '/2056/' +
          '{TileMatrix}/{TileCol}/{TileRow}.').replace('http:', location.protocol) + extension,
    tileGrid: tileGrid,
    projection: projection,
    layer: options['serverLayerName'] ? options['serverLayerName'] : layer,
    requestEncoding: 'REST'
  }));
};

// We retrieve parameters from URL
var lang = getUrlParam('lang') || 'en';
var layer = getUrlParam('layer');
var timestamp = getUrlParam('timestamp');
var format = getUrlParam('format');

// We define some global view variables
var RESOLUTIONS = [
  4000, 3750, 3500, 3250, 3000, 2750, 2500, 2250, 2000, 1750, 1500, 1250,
  1000, 750, 650, 500, 250, 100, 50, 20, 10, 5, 2.5, 2, 1.5, 1, 0.5, 0.25, 0.1
];
var extent = [2420000, 130000, 2900000, 1350000];
var projection = ol.proj.get('EPSG:2056');
projection.setExtent(extent);
var matrixIds = [];
for (var i = 0; i < RESOLUTIONS.length; i++) {
  matrixIds.push(i);
}

// We add a basic map
var baseConfig = {
  "attribution": "swisstopo",
  "format": "jpeg",
  "serverLayerName": "ch.swisstopo.pixelkarte-grau",
  "attributionUrl": "https://www.swisstopo.admin.ch/internet/swisstopo/fr/home.html",
  "timestamps": [
    "current"
  ],
  "label": "ch.swisstopo.pixelkarte-farbe_farbe",
  "type": "wmts"
};

var baseLayer = new ol.layer.Tile({
  source: wmtsSource(baseConfig.serverLayerName, baseConfig)
});

var wmsLayer = new ol.layer.Image({
  extent: extent,
  source: new ol.source.ImageWMS({
    url: 'https://wms.geo.admin.ch/',
    ratio: 1.0,
    projection: 'EPSG:2056',
    params: {
      'LAYERS': ['org.epsg.grid_21781'],
      'FORMAT': 'image/png',
      'TILED': false
    },
    serverType: 'mapserver'
  })
});

var map = new ol.Map({
  layers: [baseLayer, wmsLayer],
  target: 'map',
  logo: false,
  controls: ol.control.defaults({
    attributionOptions: ({
      collapsible: false
    })
  }).extend([
    new ol.control.ScaleLine({
      units: 'metric'
    })
  ]),
  view: new ol.View({
    center: [2600000, 1200000],
    resolutions: RESOLUTIONS,
    projection: projection,
    resolution: 250
  })
});

var addLayer = function(layerId, timestamp, format) {
  // We add the layer defined in the url
  var layerConfig = config[layerId];
  layerConfig.timestamp = timestamp;
  layerConfig.format = format || layerConfig.format;
  var olLayer = new ol.layer.Tile({
    source: wmtsSource(layerConfig.serverLayerName, layerConfig)
  });
  if (layerConfig.background) {
    map.getLayers().setAt(0, olLayer);
  } else if (map.getLayers().getLength() == 2) {
    map.getLayers().insertAt(1, olLayer);
  } else {
    map.getLayers().setAt(1, olLayer);
  }
};
// We define special configurations for cadastralwebmap
var cadastralCfg = {
  attribution: "Mensuration officielle suisse / FL",
  timestamps: ["current"],
  background: false,
  format: "png",
  serverLayerName: "ch.kantone.cadastralwebmap-farbe",
  label: "CadastralWebMap",
  hasLegend: true,
  type: "wmts"
};

// We get the official layersConfig and display all the layers (with their timestamps) available.
var config;
$.ajax({
  url: SERVICE_BASE_URL +  "rest/services/api/MapServer/layersConfig?lang=" + lang
}).done(function(data) {
  config = data;
  var content = '';
  var nbLayers = 0;
  var nbTimestamps = 0;
  data['ch.kantone.cadastralwebmap-farbe'] = cadastralCfg;
  data['ch.swisstopo.zeitreihen'].format = 'png';
  $.each(data, function(layerId, layerConfig) {
    if (layerConfig.type == 'wmts' && layerConfig.timestamps) {
      nbLayers++;
      nbTimestamps += layerConfig.timestamps.length;
      content += '<b>' + layerConfig.label + '</b>   (' + layerConfig.serverLayerName + ')<br>';
      layerConfig.timestamps.forEach(function(timestamp) {
        content +=
          '<a href="#" onclick="addLayer(\''+ layerId + '\', ' + timestamp + ', \'' + layerConfig.format + '\')">' +
          '[' + timestamp + ']' +
          '</a>';
      });
      content += '<br><br>';
    }
  });
  $('#layers').html('<h3>All ' + nbLayers + ' available layers and ' + nbTimestamps + ' timestamps')
    .append(content);
  
  // Add layer from url parameters
  if (layer) {
    addLayer(layer, timestamp || data[layer].timestamps[0], format || data[layer].format);
  }
});




            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console