How to create a union of several polygons


Creating a union of several polygons

The following code example constructs a polygon representing the topological union of several polygons. The source polygons come from a feature class. References to the polygons are inserted into a geometry bag. The geometry bag is then used as the input parameter to the ConstructUnion method.
The spatial reference of the geometry bag is defined before adding geometries to it.
[Java]
static IPolygon geometryBag_Example(IFeatureClass featureClass)throws Exception{

    //Check input objects.
    if (featureClass == null)
        return null;


    IGeoDataset geoDataset = (IGeoDataset)featureClass;
    ISpatialFilter queryFilter = new SpatialFilter();

    //Set the properties of the spatial filter here.
    IGeometry geometryBag = new GeometryBag();

    //Define the spatial reference of the bag before adding geometries to it.
    geometryBag.setSpatialReferenceByRef(geoDataset.getSpatialReference());

    //Use a nonrecycling cursor so each returned geometry is a separate object. 
    IFeatureCursor featureCursor = featureClass.search(queryFilter, false);

    IGeometryCollection geometryCollection = (IGeometryCollection)geometryBag;
    IFeature currentFeature = featureCursor.nextFeature();

    while (currentFeature != null){
        //Add a reference to this feature's geometry into the bag.
        //You don't specify the before or after geometry (missing),
        //so the currentFeature.Shape IGeometry is added to the end of the geometryCollection.
        geometryCollection.addGeometry(currentFeature.getShape(), null, null);

        currentFeature = featureCursor.nextFeature();
    }

    // Create the polygon that will be the union of the features returned from the search cursor.
    // The spatial reference of this feature does not need to be set ahead of time. The 
    // ConstructUnion method defines the constructed polygon's spatial reference to be the same as 
    // the input geometry bag.
    ITopologicalOperator unionedPolygon = new Polygon();
    unionedPolygon.constructUnion((IEnumGeometry)geometryBag);

    return (IPolygon)unionedPolygon;
}






Development licensingDeployment licensing
ArcGIS for Desktop BasicArcGIS for Desktop Basic
ArcGIS for Desktop StandardArcGIS for Desktop Standard
ArcGIS for Desktop AdvancedArcGIS for Desktop Advanced
Engine Developer KitEngine