使用 turf.js 库中的 union 函数,并确保传递给它的 GeoJSON 对象都是有效的。这可以通过使用 turf.js 中的 isValid 函数来实现。示例代码如下:
// 导入 turf.js 库 const turf = require('@turf/turf');
// 定义两个 GeoJSON 对象作为示例 const poly1 = { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [-113.4, 53.5], [-113.4, 53.6], [-113.2, 53.6], [-113.2, 53.5], [-113.4, 53.5] ] ] } };
const poly2 = { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [-113.3, 53.4], [-113.3, 53.7], [-113.1, 53.7], [-113.1, 53.4], [-113.3, 53.4] ] ] } };
// 检查两个 GeoJSON 对象的有效性 if (turf.isValid(poly1) && turf.isValid(poly2)) { // 合并两个区域 const unioned = turf.union(poly1, poly2); console.log(unioned); } else { console.log('One or more of the GeoJSON features is not valid.'); }