我正在尝试在网络组件内使用传单。这是我的代码。
我已将标准示例复制粘贴到传单网站上,但给它一个 HTMLElement 而不是 id 字符串。
class InfoWithMap extends HTMLElement {
constructor(){
super().attachShadow({mode: 'open'});
}
connectedCallback(){
let container = `
<style>
#map {
height: 500px;
width: 100%;
}
</style>
<div id='container'>
<div>Name: Someone</div>
<div>Location: Some place</div>
<div id='map'></div>
</div>`
this.shadowRoot.innerHTML = container;
let mapDiv = this.shadowRoot.getElementById('map');
var map = L.map(mapDiv).setView([51.505, -0.09], 19);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
}
}
window.customElements.define('info-with-map', InfoWithMap);
let m = document.createElement('info-with-map');
document.getElementById('main').append(m);
#main {
width: 50%;
}
<!-- https://leafletjs.com/examples/quick-start/ -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""></script>
<div id="main">
</div>
但是,正如您所看到的,地图没有正确显示。
知道设置有什么问题吗?
编辑: 在这里内联输出的有限空间中可能不太容易看出问题。因此,这里是用于比较具有和不具有 Web 组件的 Leaflet 输出的代码笔。
请注意,在 Web 组件的输出中,图块未正确显示。
您正在将 Leaflet CSS 添加到全局范围;但全局CSS无法设置shadowDOM的样式
您需要在 ShadowDOM 内部加载 CSS,因为它会安排所有异步加载的 IMG 图块在insideshadowDOM。
您也不想想要在 HTML 中加载
<script src=".../leaflet.js">
。<style>
maps { display:grid; grid:90px 90px/1fr 1fr; gap:5px; background:green }
</style>
<maps>
<leaflet-map coords="52.09,5.12"></leaflet-map><leaflet-map coords="52.372,4.885"></leaflet-map>
<leaflet-map coords="51.924,4.47"></leaflet-map><leaflet-map coords="50.85,5.69"></leaflet-map>
</maps>
<script>
customElements.define('leaflet-map', class extends HTMLElement {
constructor() {
super().attachShadow({mode: 'open'}).innerHTML =
`<style>.leaflet-control-zoom{display:none}</style>` +
`<link rel="stylesheet" href="//cdn.skypack.dev/leaflet/dist/leaflet.css">` +
`<div style="height:100%"/>`;
}
connectedCallback() {
if (window.L) this.render(); // if Leaflet already loaded as global Object
else document.head.append(Object.assign(document.createElement("script"),{
src : "//unpkg.com/leaflet@latest/dist/leaflet.js",
onload : () => this.render() }))
}
render(){
this.map = L.map(this.shadowRoot.querySelector('div'));
this.map.addLayer(L.tileLayer("//tile.osm.org/{z}/{x}/{y}.png", { }));
this.setView( ...this.getAttribute("coords").split(",") );
}
setView( lat, lon, zoom=this.getAttribute("zoom")||13 ){
this.map.setView([lat, lon], zoom);
}
});
</script>