Attach a popup to a marker instance
Attach a Popup to a Marker and display it when the user clicks on the Marker.
NPM module setup
npm install --save @maptiler/sdk
import { Map, MapStyle, config, Popup } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const monument = [-77.0353, 38.8895];
const map = new Map({
container: 'map',
style: MapStyle.STREETS,
center: monument,
zoom: 15
});
// create the popup
const popup = new Popup({ offset: 25 }).setText(
'Construction on the Washington Monument began in 1848.'
);
// create DOM element for the marker
const el = document.createElement('div');
el.id = 'marker';
// create the marker
new maptilersdk.Marker({element: el})
.setLngLat(monument)
.setPopup(popup) // sets a popup on this marker
.addTo(map);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Attach a popup to a marker instance</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
body {margin: 0; padding: 0;}
#map {position: absolute; top: 0; bottom: 0; width: 100%;}
#marker {
background-image: url('https://docs.maptiler.com/sdk-js/assets/washington-monument.jpg');
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
.maplibregl-popup {
max-width: 200px;
}
Related examples
Weather custom popup
ExamplesCreate highly customizable popups for weather maps using MarkerLayout.