import { generateUUID } from "../src/tool"; /** * 使用turf工具进行切割面 * @param line 线段数据 * @param outerPolygon 面数据 * return 返回切割的面数据 */ export function splitPolygonByLine(line,outerPolygon){ let truncatedSplitter = turf.truncate(turf.lineString(outerPolygon.geometry.coordinates[0]), {precision: 7}); //求交点 let intersectCollection = turf.lineIntersect(line, truncatedSplitter); if (intersectCollection.features.length < 2) { return null; } //将点合并成MultiPoint let intersectCombined = turf.combine(intersectCollection).features[0]; //分别获取切割线 let outerPieceCollection = turf.lineSplit(line, intersectCombined); let splitterPieceCollection = turf.lineSplit(truncatedSplitter, intersectCombined); //将所有的线段放到一起 let pieceCollection = turf.featureCollection(outerPieceCollection.features.concat(splitterPieceCollection.features)); //使用turf将闭合线组成多边形 let polygonCollection = turf.polygonize(pieceCollection); //对多边形进行判断,切割外的多边形丢弃 // let innerPolygons = polygonCollection.features.filter(polygon => { // let center = turf.centroid(polygon); // return turf.booleanWithin(center, outerPolygon); // }); let innerPolygons = polygonCollection.features; //处理镂空数据(多处镂空数据会导致计算错误,因为polygonize方法无法正常的返回数据) if(outerPolygon.geometry.coordinates?.length > 1){ //获取镂空的面数据 let holeCollection = turf.featureCollection(outerPolygon.geometry.coordinates.slice(1).map(item=>turf.polygon([item]))); //剔除掉镂空的部分数据 innerPolygons = innerPolygons.map(polygon => { let diff = polygon; turf.featureEach(holeCollection, (hole) => { diff = turf.difference(diff, hole); }); return diff; }); } innerPolygons.forEach((item,index)=>{ innerPolygons[index].properties.id = generateUUID(); }) return innerPolygons; } export function splitPolygonByFill(fill,outerPolygon){ var polygon1 = turf.polygon(fill.geometry.coordinates); // var polygon1 = turf.polygon( // [ // [ // [ // 118.08246593377775, // 35.22214906870923 // ], // [ // 118.0824468053414, // 35.2221025269492 // ], // [ // 118.08255783344151, // 35.22206277960647 // ], // [ // 118.08258527859043, // 35.22213378126961 // ], // [ // 118.08246593377775, // 35.22214906870923 // ] // ] // ] // ) var polygon2 = turf.polygon(outerPolygon.geometry.coordinates); // var polygon2 = turf.polygon( // [ // [ // [ // 118.082358, // 35.222126 // ], // [ // 118.082517, // 35.222061 // ], // [ // 118.082535, // 35.222098 // ], // [ // 118.082372, // 35.222163 // ], // [ // 118.082358, // 35.222126 // ] // ] // ] // ) var difference = turf.difference(polygon1, polygon2); console.log("difference123",difference); return difference; }