Application Development and Automation Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

How do I create a custom Leaflet map component

LynnS1
Product and Topic Expert
Product and Topic Expert
0 Likes
1,324

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/leaflet@1.7.1/dist/leaflet.js';
const leafletCSS = 'https://unpkg.com/leaflet@1.7.1/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);
}
};

1 REPLY 1
Read only

0 Likes
1,127

Any luck in finding solution to this Maps requirement ?