创建可拖动点
创建用户可以拖动的GeoJSON点;
<!DOCTYPE html>
<html lang="en">
<head>
<title>创建可拖动点</title>
<meta property="og:description" content="创建用户可以拖动的GeoJSON点" />
<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>
<div id="map"></div>
<script>
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 canvas = map.getCanvasContainer();
const geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [0, 0]
}
}
]
};
function onMove(e) {
const coords = e.lngLat;
// 设置UI指示器
canvas.style.cursor = 'grabbing';
// 更新GeoJSON数据
geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
// 更新源
map.getSource('point').setData(geojson);
}
function onUp(e) {
const coords = e.lngLat;
// 打印经纬度坐标
console.log(`Longitude: ${coords.lng} Latitude: ${coords.lat}`);
canvas.style.cursor = '';
// 解绑移动事件
map.off('mousemove', onMove);
map.off('touchmove', onMove);
}
function onDown() {
canvas.style.cursor = 'grab';
map.on('mousemove', onMove);
map.on('touchmove', onMove);
map.once('mouseup', onUp);
map.once('touchend', onUp);
}
map.on('load', () => {
// 添加GeoJSON源
map.addSource('point', {
'type': 'geojson',
'data': geojson
});
// 添加点图层
map.addLayer({
'id': 'point',
'type': 'circle',
'source': 'point',
'paint': {
'circle-radius': 10,
'circle-color': '#F84C4C' // 红色
}
});
// 当点击圆圈时进行交互
map.on('mouseenter', 'point', () => {
canvas.style.cursor = 'move';
});
map.on('mouseleave', 'point', () => {
canvas.style.cursor = '';
});
map.on('mousedown', 'point', (e) => {
// 防止地图拖动
e.preventDefault();
canvas.style.cursor = 'grab';
map.on('mousemove', onMove);
map.once('mouseup', onUp);
});
map.on('touchstart', 'point', (e) => {
if (e.points.length !== 1) return;
// 防止地图拖动
e.preventDefault();
map.on('touchmove', onMove);
map.once('touchend', onUp);
});
});
</script>
</body>
</html>