How do I create a custom Leaflet map component

Hello team,

I am trying to create a custom component for the marketplace that simply displays points on a leaflet map. I try to create a new component by converting a container into a new component. I then add a custom javascript in the logic that defines the leaflet map when the page is mounted. I set the style to a fixed height and width of 500 px. But when I test, nothing shows.

Has anyone tried this?

Below is the code:

const leafletCDN = ‘https://unpkg.com/[email protected]/dist/leaflet.js‘;
const leafletCSS = ‘https://unpkg.com/[email protected]/dist/leaflet.css‘;

// Load Leaflet CSS
const link = document.createElement(‘link’);
link.rel = ‘stylesheet’;
link.href = leafletCSS;
document.head.appendChild(link);

// Inject custom CSS
const style = document.createElement(‘style’);
style.innerHTML = `
.leaflet-container {
width: 100%;
height: 500px;
}
`;
document.head.appendChild(style);

// Load Leaflet JS
const script = document.createElement(‘script’);
script.src=leafletCDN;
document.head.appendChild(script);

script.onload = () => {
// Locate the map container within the custom component
const mapContainer = document.querySelector(‘[data-component-name=”LeafletMap”] > div’);

if (mapContainer) {
mapContainer.className = ‘leaflet-container’;
const latitude = 51.505; // Fixed latitude for testing
const longitude = -0.09; // Fixed longitude for testing
const zoom = 13; // Fixed zoom level for testing

const map = L.map(mapContainer).setView([latitude, longitude], zoom);

L.tileLayer(‘https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png’, {
attribution: ‘© OpenStreetMap contributors’
}).addTo(map);
}
};

Scroll to Top