var line = turf.lineString([[8940117.74537665,5936319.233970245],[10407708.688452033,5740640.441560194],[10466412.326175049,5359066.796360594]]);
var buffered = turf.buffer(line , val, {units: 'kilometers'});
//创建数据geojson对象和数据源对象
var format = new GeoJSON();
var source = new VectorSource({ wrapX: false });
// //读取geojson数据
var lineFeature = format.readFeature(line);
var bufferFeature = format.readFeature(buffered);
// //将数据添加数据源的
source.addFeature(lineFeature);
source.addFeature(bufferFeature);
var test = new VectorLayer({ source: source })
this.map.addLayer(test)
并且还如下得错误
然后开始在网上查资料后,知道turf缓冲区不能用EPSG:3857的坐标系,需要转成EPSG:4326(关于坐标系不清楚得,可以看
这里
)
然后我转过后再试验
let coordinates = '[[8940117.74537665,5936319.233970245],[10407708.688452033,5740640.441560194],[10466412.326175049,5359066.796360594]]';
let bufferCoordinates = [],pointTransform=[];
for (var i = 0; i < coordinates.length; i++) {
pointTransform = transform(coordinates[i], "EPSG:3857", "EPSG:4326");
bufferCoordinates.push(pointTransform);
var line = turf.lineString(bufferCoordinates);
var buffered = turf.buffer(line , val, {units: 'kilometers'});
//创建数据geojson对象和数据源对象
var format = new GeoJSON();
var source = new VectorSource({ wrapX: false });
// //读取geojson数据
var lineFeature = format.readFeature(line);
var bufferFeature = format.readFeature(buffered);
// //将数据添加数据源的
source.addFeature(lineFeature);
source.addFeature(bufferFeature);
var test = new VectorLayer({ source: source })
this.map.addLayer(test)
到了这里发现虽然不报错了,但是结果还是不出来,然后这样看来代码没问题,我这个时候就开始写
demo
,然后在demo中查看发现运行是没问题得;
那就奇了怪了,到底是哪里还有问题,最后又看了一遍官方文档,然后加上了以下两行代码
lineFeature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
bufferFeature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
再次运行,成功出现缓冲区:
参考:
openlayers+turf.js实现缓冲区得绘制