Example of a custom element with a map.
The example creates and registers a custom element, ol-map
, which contains a simple map. Note: Only works in browsers that supports ShadowRoot
.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Custom map element</title>
<!-- 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=fetch,requestAnimationFrame,Element.prototype.classList,URL"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<ol-map id="map" class="map"></ol-map>
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
class OLComponent extends HTMLElement {
constructor() {
super();
this.shadow = this.attachShadow({mode: 'open'});
const link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', 'css/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);
{
"name": "es2015-custom-element",
"dependencies": {
"ol": "6.3.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}