Jsts
Runnable OpenLayers example: Jsts. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
示例:几何缓冲 — OpenLayers jsts
核心逻辑:绘制多边形后对每个顶点采样并求凸包,得到向外扩张的缓冲区几何
依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>几何缓冲</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
html,body{height:100%;margin:0}
body{display:flex;flex-direction:column;overflow:hidden;
font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
.bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
display:flex;gap:14px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
.bar label{display:flex;gap:6px;align-items:center}
.bar button{font:inherit;padding:3px 9px;border:1px solid #ccd2da;background:#fff;
border-radius:3px;cursor:pointer;color:#2b3140}
#map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
<label>缓冲距离 <input type="range" id="dist" min="100" max="2000" step="50" value="600"><b id="distVal">600 m</b></label>
<button id="clear">清空</button>
<span id="info">在地图上画一个多边形</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
'use strict';
if (typeof ol === 'undefined') {
document.getElementById('map').innerHTML =
'<div style="padding:20px;color:#b42318">OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
return;
}
var source = new ol.source.Vector();
var bufferSource = new ol.source.Vector();
var polyStyle = new ol.style.Style({
fill: new ol.style.Fill({ color: 'rgba(31,95,208,0.20)' }),
stroke: new ol.style.Stroke({ color: '#1f5fd0', width: 2 })
});
var bufferStyle = new ol.style.Style({
fill: new ol.style.Fill({ color: 'rgba(232,89,12,0.14)' }),
stroke: new ol.style.Stroke({ color: '#e8590c', width: 2, lineDash: [8, 5] })
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}), opacity: 0.7 }),
new ol.layer.Vector({ source: bufferSource, style: bufferStyle }),
new ol.layer.Vector({ source: source, style: polyStyle })
],
view: new ol.View({
center: ol.proj.fromLonLat([116.391, 39.907]),
zoom: 13,
minZoom: 2
}),
controls: ol.control.defaults.defaults({ attribution: false })
});
/* Andrew 单调链凸包,输入 [[x,y], ...] */
function convexHull(points) {
var pts = points.slice().sort(function (a, b) {
return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0];
});
if (pts.length < 3) return pts;
function cross(o, a, b) {
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
}
var lower = [];
pts.forEach(function (p) {
while (lower.length >= 2 &&
cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
});
var upper = [];
pts.slice().reverse().forEach(function (p) {
while (upper.length >= 2 &&
cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
});
lower.pop();
upper.pop();
return lower.concat(upper);
}
/* 顶点圆周采样后求凸包,等价于外扩缓冲的近似 */
function makeBuffer(polygon, distance) {
var ring = polygon.getCoordinates()[0];
var samples = [];
var SEG = 24;
ring.forEach(function (coord) {
for (var k = 0; k < SEG; k++) {
var a = k / SEG * Math.PI * 2;
samples.push([
coord[0] + Math.cos(a) * distance,
coord[1] + Math.sin(a) * distance
]);
}
});
var hull = convexHull(samples);
if (hull.length < 3) return null;
hull.push(hull[0]);
return new ol.geom.Polygon([hull]);
}
function rebuild() {
var distance = Number(document.getElementById('dist').value);
document.getElementById('distVal').textContent = distance + ' m';
bufferSource.clear();
source.getFeatures().forEach(function (f) {
var geom = f.getGeometry();
if (!geom || geom.getType() !== 'Polygon') return;
var buf = makeBuffer(geom, distance);
if (buf) {
var feature = new ol.Feature({ geometry: buf });
feature.setStyle(bufferStyle);
bufferSource.addFeature(feature);
}
});
}
var draw = new ol.interaction.Draw({
source: source,
type: 'Polygon'
});
draw.on('drawend', function (evt) {
var geom = evt.feature.getGeometry().clone();
source.clear();
source.addFeature(new ol.Feature({ geometry: geom }));
rebuild();
document.getElementById('info').textContent = '缓冲区半径 ' +
document.getElementById('dist').value + ' m';
});
map.addInteraction(draw);
/* 预置一个多边形,打开即可看到缓冲效果 */
var seed = new ol.geom.Polygon([[
[116.380, 39.900], [116.402, 39.900], [116.405, 39.914],
[116.386, 39.916], [116.380, 39.900]
]]).transform('EPSG:4326', 'EPSG:3857');
source.addFeature(new ol.Feature({ geometry: seed }));
rebuild();
document.getElementById('dist').addEventListener('input', rebuild);
document.getElementById('clear').addEventListener('click', function () {
source.clear();
bufferSource.clear();
document.getElementById('info').textContent = '在地图上画一个多边形';
});
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.