How to create a simple square polygon and add it to a feature class.

6640
3
Jump to solution
12-05-2016 11:10 AM
BrandonZaitz
New Contributor III

So, the code below is a part of a much larger script. Within that larger script i have already successfully created and written geometries to two polyline feature classes and two point feature classes. I would like to now create and write geometries to a polygon feature class. However, every time i attempt to use "arcpy.Polygon()" the resulting object is empty despite the point objects and array object that i pass to "arcpy.Polygon()" not being empty. Am i missing something here? Every time i try and create a polygon object it is empty no matter what i pass to it. Any help would be greatly appreciated.

import os, arcpy

infc = r"C:\Users\User\GIS\single_section.shp"
polygons = r"C:\Users\User\GIS\polygons.shp"

spatialref = arcpy.Describe(infc).spatialReference

if arcpy.Exists(polygons):
 arcpy.Delete_management(polygons)
 
arcpy.CreateFeatureclass_management(*os.path.split(polygons), geometry_type="Polygon", spatial_reference=spatialref.factoryCode)

icursor = arcpy.da.InsertCursor(polygons, ["SHAPE@"])

TLX = -104.357483001
TLY = 32.2242740047
TRX = -104.341346746
TRY = 32.2241446297
BRX = -104.356403497
BRY = 32.2233637742
BLX = -104.357479189
BLY = 32.2233727547

array = arcpy.Array()
array.add(arcpy.Point(TLX,TLY))
array.add(arcpy.Point(TRX,TRY))
array.add(arcpy.Point(BRX,BRY))
array.add(arcpy.Point(BLX,BLY))
array.add(arcpy.Point(TLX,TLY))

polygon = arcpy.Polygon(array)

icursor.insertRow([polygon])
1 Solution

Accepted Solutions
DarrenWiens2
MVP Honored Contributor

Try specifying the spatial reference when you create your polygon:

polygon = arcpy.Polygon(array,spatialref)

View solution in original post

3 Replies
DarrenWiens2
MVP Honored Contributor

Try specifying the spatial reference when you create your polygon:

polygon = arcpy.Polygon(array,spatialref)
BrandonZaitz
New Contributor III

Thanks for the reply. Yeah, that solved my problem. I actually managed to figure it out just a few minutes before seeing your reply. This was really vexing me for a few hours. Just seems strange to me that i would have to define a spatial reference when creating a polygon object but not a polyline...

0 Kudos
DarrenWiens2
MVP Honored Contributor

I agree that it is inconsistent when you require a spatial reference and when it will let you get away without one, but I've decided that it's worth it to just include a spatial reference every time you a.) create a geometry object, and b.) create a Search or Update cursor.