绘制一个圆形
基于用户定义的半径创建圆形;
<!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>
<script src="https://unpkg.com/@turf/turf@6/turf.min.js"></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<style>
.distance-container {
position: absolute;
top: 10px;
left: 10px;
z-index: 1;
}
.distance-container > * {
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 11px;
line-height: 18px;
display: block;
margin: 0;
padding: 5px 10px;
border-radius: 3px;
}
</style>
<div id="map"></div>
<div id="distance" class="distance-container"></div>
<script>
const map = new maplibregl.Map({
container: 'map',
style:
'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [-90.096962, 29.957853],
zoom: 10.74
});
const distanceContainer = document.getElementById('distance');
// GeoJSON对象,用于绘制半径圈和点
const geojson = {
'type': 'FeatureCollection',
'features': []
};
// 用于计算总距离
let linestring = {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': []
}
};
map.on('load', () => {
map.addSource('geojson', {
'type': 'geojson',
'data': geojson
});
// 添加表示半径圆的填充图层
map.addLayer({
id: 'measure-points',
type: 'circle',
source: 'geojson',
paint: {
'circle-radius': 5,
'circle-color': '#000'
},
filter: ['in', '$type', 'Point']
});
map.addLayer({
id: 'measure-polygon',
type: 'fill',
source: 'geojson',
layout: {},
paint: {
'fill-color': '#088',
'fill-opacity': 0.8
},
filter: ['==', '$type', 'Polygon']
});
map.addLayer({
id: 'measure-polygon-outline',
type: 'line',
source: 'geojson',
layout: {},
paint: {
'line-color': '#088',
'line-width': 1,
'line-opacity': 1
},
filter: ['==', '$type', 'Polygon']
});
// 在双击时删除图层
map.on('dblclick', () => {
geojson.features = [];
linestring.geometry.coordinates = [];
distanceContainer.innerHTML = '';
map.getSource('geojson').setData(geojson);
});
map.on('click', (e) => {
// 无论有多少点(包括单击本身),我们总是使用最后一点和鼠标坐标作为半径的边界
const clickLngLat = [e.lngLat.lng, e.lngLat.lat];
linestring.geometry.coordinates = [clickLngLat];
// 使用点击位置为圆心创建一个20英里半径的圆
const center = turf.point(clickLngLat);
const radius = 20;
const options = {
steps: 64,
units: 'miles'
};
const circle = turf.circle(center, radius, options);
if (geojson.features.length > 1) geojson.features.pop();
geojson.features.push(circle);
geojson.features.push(center);
map.getSource('geojson').setData(geojson);
// 更新显示的半径距离(假设为英里)
distanceContainer.innerHTML = `<p>半径: ${radius} 英里</p>`;
});
});
</script>
</body>
</html>