Popups
Simple popup
Popup is a custom HTML element that is bound to a specific location on the map. To add a popup to the map, use the HtmlMarker() method and specify the coordinates and HTML markup:
const popup = new mapgl.HtmlMarker(map, {
coordinates: [55.31878, 25.23584],
html: `<div class="popup">
<div class="popup-content">
This is a text of the popup
</div>
<div class="popup-tip"></div>
</div>`,
});
HTML element inside the popup can be customized with CSS as usual.
Events
You can add interactive elements inside the popup. To add a listener, use the getContent()
method to get the HTML element inside the popup and then add the listener as usual:
const popup = new mapgl.HtmlMarker(map, {
coordinates: [55.31878, 25.23584],
html: `<div class="popup">
<div class="popup-content">
This is a text of the popup
<button>Click me</button>
</div>
<div class="popup-tip"></div>
</div>`,
});
popup
.getContent()
.querySelector('button')
.addEventListener('click', () => alert('The button has been clicked!'));
Marker with a popup
To show a popup after clicking on a Marker, you need to add three listeners: one on the Marker (to show the popup), and one each on the map and popup itself (to hide the popup).
const marker = new mapgl.Marker(map, {
coordinates: [55.31878, 25.22438],
});
const popupHtml = popup.getContent();
hidePopup();
marker.on('click', () => (popupHtml.style.display = 'block'));
popupHtml.querySelector('.popup-close').addEventListener('click', hidePopup);
map.on('click', hidePopup);
function hidePopup() {
popupHtml.style.display = 'none';
}
Complex elements in a popup
You can also pass an HTML element as the html
parameter. For example, you can use a canvas with animation inside a popup:
const canvas = document.createElement('canvas');
canvas.width = 70;
canvas.height = 70;
canvas.style.position = 'absolute';
canvas.style.transform = 'translate(-50%, -50%)';
canvas.style.border = '1px solid';
canvas.style.background = '#fff';
const ctx = canvas.getContext('2d');
function render() {
requestAnimationFrame(render);
ctx.clearRect(0, 0, 70, 70);
ctx.beginPath();
const radius = (Date.now() / 70) % 35;
ctx.arc(35, 35, radius, 0, Math.PI * 2);
ctx.stroke();
}
requestAnimationFrame(render);
const popup = new mapgl.HtmlMarker(map, {
coordinates: [55.31878, 25.23584],
html: canvas,
});