Skip to content

Draggable Marker

Set draggable: true and listen for the drag event to read the marker position live as it moves.

import { MaptoolkitLogoControl } from 'https://cdn.jsdelivr.net/npm/@maptoolkit/maplibre-gl-logo/+esm';
const map = new maplibregl.Map({ container: 'map', attributionControl: { customAttribution: '' }, style: 'https://styles.maptoolkit.org/summer.json', center: [4.9041, 52.3676], zoom: 12 }); // Amsterdam
const marker = new maplibregl.Marker({ draggable: true }).setLngLat([4.9041, 52.3676]).addTo(map);
const coords = document.getElementById('coords');
function report() { const l = marker.getLngLat(); coords.textContent = 'Lng: ' + l.lng.toFixed(4) + '  Lat: ' + l.lat.toFixed(4); }
marker.on('drag', report);
report();
map.addControl(new MaptoolkitLogoControl());
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/maplibre-gl.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/maplibre-gl.css" />
  <style>
    html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
    #map { width: 100%; height: 100%; }
  </style>
</head>
<body>
  <pre id="coords" style="position:absolute;bottom:10px;left:10px;z-index:1;margin:0;background:#fff;padding:6px 8px;border-radius:4px;font:12px monospace;box-shadow:0 1px 4px rgba(0,0,0,.3)"></pre>
  <div id="map"></div>
  <script type="module">
import { MaptoolkitLogoControl } from 'https://cdn.jsdelivr.net/npm/@maptoolkit/maplibre-gl-logo/+esm';
const map = new maplibregl.Map({ container: 'map', attributionControl: { customAttribution: '' }, style: 'https://styles.maptoolkit.org/summer.json', center: [4.9041, 52.3676], zoom: 12 }); // Amsterdam
const marker = new maplibregl.Marker({ draggable: true }).setLngLat([4.9041, 52.3676]).addTo(map);
const coords = document.getElementById('coords');
function report() { const l = marker.getLngLat(); coords.textContent = 'Lng: ' + l.lng.toFixed(4) + '  Lat: ' + l.lat.toFixed(4); }
marker.on('drag', report);
report();
map.addControl(new MaptoolkitLogoControl());
  </script>
</body>
</html>