原文链接及内容

该示例创建并注册了一个自定义元素ol-map
,其中包含一个可访问的 OpenLayers 地图。因此,ol-map
元素的tabindex
属性设置为“0”
。因此地图可以获得焦点,从而允许使用键盘进行地图导航。使用+和-键放大和缩小,使用箭头键平移地图。注意:仅适用于支持ShadowRoot
的浏览器。
main.js
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import Map from 'ol/Map.js'; import OSM from 'ol/source/OSM.js'; import TileLayer from 'ol/layer/Tile.js'; import View from 'ol/View.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
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <!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>
|