原文链接及内容

这个例子创建并注册了一个自定义元素ol-map
,并为它引入了一幅简单的地图。注意:仅适用于支持ShadowRoot
的浏览器。
注:关于ShadowRoot
的内容请参见MDN的解释:https://developer.mozilla.org/zh-CN/docs/Web/API/ShadowRoot ,以及掘金上一篇不错的博客能够更通俗地进行了讲解:https://juejin.cn/post/7137112423613333541 。
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
| 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';
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 div = document.createElement('div'); div.style.width = '100%'; div.style.height = '100%'; this.shadow.appendChild(div);
this.map = new Map({ target: div, 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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Custom map element</title> <link rel="stylesheet" href="node_modules/ol/ol.css"> <style> .map { width: 100%; height: 400px; } </style> </head> <body> <ol-map id="map" class="map"></ol-map> <script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script> <script type="module" src="main.js"></script> </body> </html>
|