Using geometry objects with geoprocessing tools
In many geoprocessing workflows, you may need to run a specific operation using coordinate and geometry information but don't necessarily want to go through the process of creating a new (temporary) feature class, populating the feature class with cursors, using the feature class, then deleting the temporary feature class. Geometry objects can be used instead for both input and output to make geoprocessing simpler. Geometry objects can be created from scratch using Geometry, Multipoint, PointGeometry, Polygon, or Polyline classes.
Using geometry as input
The following sample creates a polygon geometry object created using a list of x,y coordinates. The Clip tool is then used to clip a feature class with the polygon geometry object.
import arcpy # Create an Array object. # array = arcpy.Array() # List of coordinates. # coordList = ['1.0;1.0','1.0;10.0','10.0;10.0','10.0;1.0'] # For each coordinate set, create a point object and add the x- and # y-coordinates to the point object, then add the point object # to the array object. # for coordPair in coordList: x, y = coordPair.split(";") pnt = arcpy.Point(x,y) array.add(pnt) # Add in the first point of the array again to close the polygon boundary # array.add(array.getObject(0)) # Create a polygon geometry object using the array object # boundaryPolygon = arcpy.Polygon(array) # Use the geometry to clip an input feature class # arcpy.Clip_analysis("c:/data/rivers.shp", boundaryPolygon, "c:/data/rivers_clipped.shp")
Outputting geometry objects
Output geometry objects can be created by setting the output of a geoprocessing tool to an empty geometry object. When a tool is run when set to an empty geometry object, the tool returns a list of geometry objects. In the following example, the Copy Features tool is used to return a list of geometry objects, which can then be looped through to accumulate the total length of all features.
import arcpy # Create an empty Geometry object # g = arcpy.Geometry() # Run the CopyFeatures tool, setting the output to the geometry object. GeometryList # is returned as a list of geometry objects. # geometryList = arcpy.CopyFeatures_management("c:/temp/outlines.shp", g) # Walk through each geometry, totaling the length # length = 0 for geometry in geometryList: length += geometry.length print "Total length: %f" % length