1、dxf数据说明
DXF是一种开放的矢量数据格式,可以分为两类:ASCII格式和二进制格式;ASCII具有可读性好的特点,但占用的空间较大;二进制格式则占用的空间小、读取速度快。由于AutoCAD是最流行的CAD系统,DXF也被广泛使用,成为事实上的标准。绝大多数CAD系统都能读入或输出DXF文件。
2、解析库
npm install dxf-parser
3、接口
1、同步解析:parseSync
2、异步解析:parse
4、实现代码
1、读取文件并解析
const DxfParser = require('dxf-parser');
// 读取DXF文件
const fs = require('fs');
const dxfContent = fs.readFileSync('uploads/road-all2.dxf', 'utf-8');let parser = new DxfParser();// 解析DXF文件
const { layers, entities } = parser.parseSync(dxfContent);
2、读取图层实体数据,比如提取道路图层的数据
let gcd = entities.filter(item=>{return item.layer==="道路";
})
3、将道路数据转图层并存储到geojson
const calculatePoint=(center, startAngle, endAngle, radius)=> {// 将角度转换为弧度const startRadians = startAngle;const endRadians = endAngle;// 计算两角度之间的差角度let angle = endRadians - startRadians;if(angle<0){angle += Math.PI;}//302 - 32// -270// 302-9let step = angle / 20 ;let positions = [];for(let i=0;i<21;i++){let tempAngle = angle>0?startRadians + step*i:startRadians-step*i;const x = center.x + radius * Math.cos(tempAngle);const y = center.y + radius * Math.sin(tempAngle);positions.push([x,y])}return positions;}let features = gcd.map(item=>{if(item.type==="LINE"){let vertices = item.vertices;let positions = vertices.map(vertice=>{return [vertice.x, vertice.y]})return {type: "Feature",geometry: {type: "LineString",coordinates: positions,},properties: {}}} else if(item.type==="ARC"){let {radius,startAngle,endAngle,center} = item;let positions = calculatePoint(center,startAngle,endAngle,radius);return {type: "Feature",geometry: {type: "LineString",coordinates: positions,},properties: {}}}})const gcdJSON = {type: "FeatureCollection",features: features};fs.writeFile("./data/road-line.json", JSON.stringify(gcdJSON), (err) => {if(err){console.log(err.message);}console.log('写入成功');})
5、显示结果