How to draw point, line, and surface feature buffers based on openlayers
For how to draw points, lines and surfaces, the official openlayers documentation has given detailed examples:
Feature Drawing and Editing Demo.
However, the official demo does not explain in detail how to draw the buffer. I implemented the buffer drawing function based on the above official demo of the turf library, which is suitable for various elements. The code is as follows:
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer.js';
import {
GeoJSON } from 'ol/format';
import * as turf from "@turf/turf";
draw.on('drawend', function (event) {
//添加绘制要素
const vectorSource = new VectorSource();
vectorSource.addFeature(event.feature);
//读取缓冲区半径
const radiusInput = document.querySelector('#nameInput') as HTMLInputElement;
let radius:number=parseFloat(radiusInput.value) ;
//turf缓冲区分析 openlayers默认墨卡托投影
const features = vectorSource.getFeatures();
const turfLines = (new GeoJSON()).writeFeaturesObject(features, {
featureProjection: 'EPSG:3857'
});
var buffered = turf.buffer(turfLines, radius, {
units: 'meters' });
let _bufferedFeature = (new GeoJSON()).readFeatures(buffered, {
featureProjection: 'EPSG:3857'
});
//将结果存入Source
_bufferedFeature.forEach(function(feature) {
vectorSource.addFeature(feature);
});
const vectorLayer = new VectorLayer({
source: vectorSource,
style: style,
});
vectorLayer.set('name', 'temp');
map.addLayer(vectorLayer);
});
Rendering: