This simple Leaflet example works perfectly with vanilla JavaScript but does not when using Web Components (tiles show up all messed up https://imgur.com/a/ZicDrRQ).
My best guess is the way the Shadow DOM behaves with the #map
element sizing, oddly enough if we change #map
to display: flex
slightly more tiles show up but still many are missing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leaflet.js with OpenStreetMap and Geolocation as Web Component</title>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
<!-- Leaflet JS -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
</head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<body>
<geo-map></geo-map>
<script>
class GeoMap extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:host {
display: inline-block;
width: 100%;
height: 100%;
}
#map {
display: inline-block;
width: 100%;
height: 100%;
}
</style>
<div id="map"></div>
`;
}
connectedCallback() {
const mapDiv = this.shadowRoot.querySelector('#map');
const map = L.map(mapDiv);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
map.setView([34.42696537699258, -119.7175455093384], 13);
}
}
customElements.define('geo-map', GeoMap);
</script>
</body>
</html>