Edit

Custom map element with accessible map

es20152 web-component2 custom-element2 shadow-dom2 accessibility2 tabindex2

Example of a custom element with an accessible map, which can gain focus and allows keyboard based navigation.

The example creates and registers a custom element, ol-map, which contains an accessible OpenLayers map. Therefore the ol-map element has its tabindex attribute set to "0". So the map can gain the focus and thus allows map navigation with the keyboard. Use the + and - keys to zoom in and out and the arrow keys to pan the map. Note: Only works in browsers that supports ShadowRoot.

main.js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';

let map;
class OLComponent extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({mode: 'open'});
    const link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', 'theme/ol.css');
    this.shadow.appendChild(link);
    const style = document.createElement('style');
    style.innerText = `
      :host {
        display: block;
      }
    `;
    this.shadow.appendChild(style);
    const mapTarget = document.createElement('div');
    mapTarget.style.width = '100%';
    mapTarget.style.height = '100%';
    this.shadow.appendChild(mapTarget);

    this.map = new Map({
      target: mapTarget,
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      view: new View({
        center: [0, 0],
        zoom: 2,
      }),
    });
  }
}

customElements.define('ol-map', OLComponent);
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Custom map element with accessible map</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
      #map:focus {
        outline: 0.15em solid #4A74A8;
      }
    </style>
  </head>
  <body>
    <ol-map id="map" class="map" tabindex="0"></ol-map>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
{
  "name": "es2015-custom-element-a11y",
  "dependencies": {
    "ol": "10.5.0"
  },
  "devDependencies": {
    "vite": "^3.2.3"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}