在Arcgis的项目中,可以使用esri方法实现将多个polygon图形合并为一个polygon图形的功能。具体的esri方法可参见ITopologicalOperator的ConstructUnion方法。
该方法的参考说明请见:http://help.arcgis.com/en/sdk/10.0/arcobjects_net/componenthelp/index.html#/ConstructUnion_Method/002m000003vn000000/
多个polygon图形合并为一个polygon图形的功能的代码实现步骤如下:
- 实例化CLSID_GeometryBag对象并转换为(IGeometryCollectionPtr 对象。
- 将多个polygon对象逐一放到 CLSID_GeometryBag对象中。
- 实例化(CLSID_Polygon)对象并转换为ITopologicalOperatorPtr对象。
- ITopologicalOperatorPtr对象调用方法ConstructUnion,将CLSID_GeometryBag对象作为参数,合并所有加入到CLSID_GeometryBag对象中的polygon,此时,ITopologicalOperatorPtr对象就是合并后的polygon.
实例代码如下:
/**
* @brief 将多个polygon合并为一个polygon
* @param [in] ipMultiGeomCol
* @param [out] ipUnionPolygon
* @return 是否变换成功。true:成功;false:失败
*/
bool convertMultiPolygon2Polygon(const IGeometryCollectionPtr& ipMultiGeomCol, IPolygonPtr& ipUnionPolygon)
{
// 多个polygon的集合为空的场合,返回false
if (!ipMultiGeomCol)
return false;
// 取得多个polygon的个数
long geomCount = 0;
ipMultiGeomCol->get_GeometryCount(&geomCount);
// 取得多个polygon集合的参照空间
ISpatialReferencePtr ipSpRef;
if (FAILED(IGeometryPtr(ipMultiGeomCol)->get_SpatialReference(&ipSpRef)))
return false;
// 实例化CLSID_GeometryBag并转换成IGeometryCollectionPtr ,和多个polygon 的参照空间保持一致
IGeometryCollectionPtr ipProcGeomCol(CLSID_GeometryBag);
IGeometryPtr(ipProcGeomCol)->putref_SpatialReference(ipSpRef);
// 自定义lamda函数。功能:返回指定geomegry的类型
auto getGeometryType = [](IGeometryPtr ipGeometry)->esriGeometryType
{
esriGeometryType eType = esriGeometryNull;
if (!ipGeometry || FAILED(ipGeometry->get_GeometryType(&eType)))
return esriGeometryNull;
return eType;
}
// 遍历每一个子polygon图形
for (long i = 0; i < geomCount; ++i)
{
// Geometry取得失败的场合,返回false
IGeometryPtr ipChildPolygon;
if (FAILED(ipMultiGeomCol->get_Geometry(i, &ipChildPolygon)))
return false;
// Geometry的类型不是polygon的场合,返回false
if(!(ipChildPolygon && getGeometryType(ipChildPolygon) == esriGeometryPolygon))
return false;
// 将子polygon加入到CLSID_GeometryBag对象中
if (FAILED(ipProcGeomCol->AddGeometry(ipChildPolygon)))
return false;
}
// 实例化合并后的Polygon对象,并将空间参照和多个polygon保持一致
ITopologicalOperatorPtr ipTopo(CLSID_Polygon);
IGeometryPtr(ipTopo)->putref_SpatialReference(ipSpRef);
// 合并CLSID_GeometryBag对象中的多个polygon到当前polygon对象中
if (FAILED(ipTopo->ConstructUnion(IEnumGeometryPtr(ipProcGeomCol))))
return false;
// 返回合并后的polygon对象
ipUnionPolygon= ipTopo;
return ipUnionPolygon;
}