创建可拖动标记
创建一个用户可以拖动的标记;
<!DOCTYPE html>
<html lang="en">
<head>
<title>创建可拖动标记</title>
<meta property="og:description" content="创建一个用户可以拖动的标记" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/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 =
`经度: ${lngLat.lng}<br />纬度: ${lngLat.lat}`;
}
marker.on('dragend', onDragEnd);
</script>
</body>
</html>