Create a draggable Marker
Drag the marker to a new location on a map and populate its coordinates in a display.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create a draggable Marker</title>
<meta property="og:description" content="Drag the marker to a new location on a map and populate its coordinates in a display." />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<style>
.coordinates {
background: rgba(0, 0, 0, 0.5);
color: #fff;
position: absolute;
bottom: 40px;
left: 10px;
padding: 5px 10px;
margin: 0;
font-size: 11px;
line-height: 18px;
border-radius: 3px;
display: none;
}
</style>
<div id="map"></div>
<pre id="coordinates" class="coordinates"></pre>
<script>
const coordinates = document.getElementById('coordinates');
const map = new maplibregl.Map({
container: 'map',
style:
'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [0, 0],
zoom: 2
});
const marker = new maplibregl.Marker({draggable: true})
.setLngLat([0, 0])
.addTo(map);
function onDragEnd() {
const lngLat = marker.getLngLat();
coordinates.style.display = 'block';
coordinates.innerHTML =
`Longitude: ${lngLat.lng}<br />Latitude: ${lngLat.lat}`;
}
marker.on('dragend', onDragEnd);
</script>
</body>
</html>