2
votes

How to add layerswitcher in ol 6.

import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import XYZ from 'ol/source/XYZ';

  const map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      title: 'District', 
      type: 'base', 
      source: new XYZ({
           url: "http://127.0.0.1:8080/tms/1.0.0/district/distgrid" + "/{z}/{x}/{-y}.png"  ,
          })
    }),
    new TileLayer({
      title: 'Landmark',
      source: new XYZ({
           url: "http://127.0.0.1:8080/tms/1.0.0/Landmark/landmarkgrid" + "/{z}/{x}/{-y}.png"  ,
          })
    }),
    new TileLayer({
      title: 'Road',
      source: new XYZ({
           url: "http://127.0.0.1:8080/tms/1.0.0/road/roadgrid" + "/{z}/{x}/{-y}.png"  ,
          })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 1
  })
}); 

I tried the above code but I getting error ol.control.LayerSwitcher is not a constructor. I followed this example http://raw.githack.com/walkermatt/ol-layerswitcher/master/examples/layerswitcher.html

2
You can also build your own! See that video for example: youtube.com/watch?v=k4b3nqDHCIUs.k

2 Answers

1
votes

Changing OpenLayers from 6.1.1 to 6.4.3 in that example works for me, but if you are linking directly to the library be sure to specify https as browsers to not allow http libraries to be used from https html.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>OpenLayers - LayerSwitcher</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="https://openlayers.org/en/v6.4.3/css/ol.css" />
    <link rel="stylesheet" href="https://raw.githack.com/walkermatt/ol-layerswitcher/master/src/ol-layerswitcher.css" />
    <link rel="stylesheet" href="https://raw.githack.com/walkermatt/ol-layerswitcher/master/examples/layerswitcher.css" />
  </head>
  <body>
    <div id="map"></div>
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v6.4.3/build/ol.js"></script>
    <script src="https://raw.githack.com/walkermatt/ol-layerswitcher/master/dist/ol-layerswitcher.js"></script>
    <script src="https://raw.githack.com/walkermatt/ol-layerswitcher/master/examples/layerswitcher.js"></script>
  </body>
</html>
0
votes

Check this example created control and interaction for layer switcher. Switcher is made to work with layer group you can tweak to make it work on required layer/layer group. Check this Example