Creating Polygons from Coordinates

9023
13
Jump to solution
10-23-2012 05:04 AM
JamesMitchell
Deactivated User
Hello,

I am hoping for some help.

I am trying to create polygons from coordinates but the code i am using is not working correctly.

Please can someone point me in the right direction? I have tried everything example i have found on the internet.

Thank you

    coordList.append(str(row.getvalue(desc.OIDFieldName)) + "," +str(FirstVertexXpoint) + "," + str(FirstVertexYpoint))
    coordList.append(str(row.getvalue(desc.OIDFieldName)) + "," +str(ThirdVertexXpoint) + "," + str(ThirdVertexYpoint))
    coordList.append(str(row.getvalue(desc.OIDFieldName)) + "," +str(SecondVertexXpoint) + "," + str(SecondVertexYpoint))
    coordList.append(str(row.getvalue(desc.OIDFieldName)) + "," +str(FourthVertexXpoint) + "," + str(FourthVertexYpoint))
    coordList.append(str(row.getvalue(desc.OIDFieldName)) + "," +str(FirstVertexXpoint) + "," + str(FirstVertexYpoint))


    array = arcpy.Array()
    point = arcpy.Point()
    featureList = []

for feature in coordList:
     coordinates = string.split(feature,",")

     point.ID = coordinates[0]
     point.X = coordinates[1]
     point.Y = coordinates[2]
     array.add(point)

     polygon = arcpy.Polygon(array)
     #array.removeAll()

     featureList.append(polygon)
     #array.removeAll()

arcpy.CopyFeatures_management(featureList, "c:/polygons.shp")
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
T__WayneWhitley
Honored Contributor
Excellent work.  You helped me as well with troubleshooting your interesting adaptation.  Glad it works!
If you haven't already, would you please mark this thread as 'Answered' ?

EDIT:
Sorry, I'm making too many clerical errors.  For anyone else reading this, figured I should own up and fix this so as not to mislead later.

The above is an adapted script "Create a new line feature class using a text file of coordinates."
Here's the link:

Writing geometries
Resource Center » Professional Library » Geoprocessing » Geoprocessing with Python » Accessing geographic data in Python
http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z0000001v000000

The originally suggested input file for the script contains IDs to group points making up lines.  In the loop for the sample, when the ID changes, the array of points is loaded to the geometry object defining that feature...(which is loaded into the insertcursor row, then the array is 'emptied', and the next group begins loading the array).

The idea is more or less the same for loading polygon geometry (single-part, no 'holes').  James wanted each feature assigned a user-defined feature ID (FeatID).  Actually, the shared ID from the input file for the points in the group can be assigned respectively to each created polygon feature.
The script entered above shows retrieving 4 params from each line in the file:

FeatID, pnt.ID, pnt.X, pnt.Y = string.split(line,",")

But is this necessary?  Probably not if you want to maintain a '3 parameter' line file so that line is unaltered (except for the delimiter; change that according to your input file content):

pnt.ID, pnt.X, pnt.Y = string.split(line,",")

...then you can assign the feature ID directly with the following (just make sure your field type and var type match):

feat.setValue("OW_ID", ID)

No need for an 'extra' FeatID param unless for your purposes you have unique point identifiers that need to be written somewhere too.  So the 2 lines of code I added for FeatID_load = FeatID can be eliminated and the 2 lines for 'feat.setValue' can be changed to the line above (I forgot to change one of them anyway).

View solution in original post

0 Kudos
13 Replies
T__WayneWhitley
Honored Contributor
If you're assembling this code from a sample, it looks to me you have inadvertently taken the code slightly 'out of context' - you have to paste your entire code and enclose it between the
 tags, see the sticky at the very beginning of the Python forum:

http://forums.arcgis.com/threads/48475-Please-read-How-to-post-Python-code


So, for starters, you haven't defined your coord list variable or for that matter several of the other variables, and haven't looped to load points into the array.
0 Kudos
JamesMitchell
Deactivated User
Hi,

Sorry i should have explained this a bit better.

This is just the last part of the code that i cant get to work.

I have created all the variables and have a list containing the coordinates (coordList) required to create a polygon around polylines.

For each polyline the list looks like this:
['0,9953.36724322,20031.2536665', '0,9997.81733525,20052.4203769', '0,9993.08806586,20039.092436', '0,9948.63797384,20017.9257255', '0,9953.36724322,20031.2536665']

I am then trying to use these coordinates to create a polygon.

Thank you
0 Kudos
T__WayneWhitley
Honored Contributor
Loop on that list to define your pnt.X and pnt.Y point geom, appending each point object into the array object...when done adding points to the array defining a single polygon, then load the array into the poly geom object.

Make sense?  Remember for each member of the list you provided, you have to split by the comma (which in turn produces a tuple coord part (1 list of 1 each X and Y), so your X value is the 1st member [0] and your Y value is the 2nd member [1].

So say your list is called coordList, and is formatted as you have shown above, then something like:

for each in coordList:
     XYpair = each.split(',')
     pnt.X = XYpair[0]
     pnt.Y = XYpair[1]
     # load pnt object into array, etc.
0 Kudos
JamesMitchell
Deactivated User
Thank you for the help.

As you can see i tried that but the point contains the coordinates but the polygons that are created do not contain any coordinates.

Thanks again.
0 Kudos
T__WayneWhitley
Honored Contributor
Check your input coordinates - if meant to be a list of comma delimited coordinate pairs, something has gone awry...too many commas, missing digits?

You are not far off from a solution - why don't you post your entire code?
It's actually better for you if I point out where your code needs 'tweaking' rather than write the code for you.

EDIT:  Another tip, it looks like your last line Copy Features would work if you fed in the poly geom you created from the point array.  This should create a single polygon in the shapefile if you feed in the single polygon object.  It's a good test, although I cannot see the rest of your code.
0 Kudos
T__WayneWhitley
Honored Contributor
I'd like to clear up any lingering confusion - made the following test and did achieve creating the polygon.  First, a couple of notes:

- For purposes of demonstration, the coordList was corrected, replacing '0,9' with '10' (see code).
- This loads a single polygon geom in a new shapefile, although realistically if processing a number of polygons, would loop with an insertcursor, reloading the array for each polygon object...
- 'featureList' wasn't really needed, but retains the point objects and was used to fetch the 1st point to 'close' the poly....indeed, the sample at the link just below fetches it directly from the array object.

http://resources.arcgis.com/en/help/main/10.1/index.html#//018z00000061000000

Anyway hope this helps (and I'll also try to attach the resulting poly):
IDLE 2.6.5      
>>> import arcpy
>>> coordList = ['10953.36724322,20031.2536665', '10997.81733525,20052.4203769', '10993.08806586,20039.092436', '10948.63797384,20017.9257255', '10953.36724322,20031.2536665']
>>> array = arcpy.Array()
>>> point = arcpy.Point()
>>> featureList = []
>>> for each in coordList:
               XYpair = each.split(',')
               point.X = XYpair[0]
               point.Y = XYpair[1]
               featureList.append(point)
               array.add(point)
 
               
>>> array.add(featureList[0])
>>> polygon = arcpy.Polygon(array)
>>> arcpy.CopyFeatures_management(polygon, r'C:\testCopyPoly.shp')
<Result 'C:\\testCopyPoly.shp'>
0 Kudos
JamesMitchell
Deactivated User
Hi,

Thank you for the help. I have now got this working. The problem was that the "coordList" was being created within the loop ratherthan before the loop.

I am now using this cose that works. Howver i would like to give a value to each polygon.

try:
   # Open an insert cursor for the new feature class
   #
   cur = arcpy.InsertCursor(fcname)

   # Create an array and point object needed to create features
   #
   lineArray = arcpy.Array()
   pnt = arcpy.Point()

   # Initialize a variable for keeping track of a feature's ID.
   #
   ID = -1
   for line in coordList: # Open the input file
      # set the point's ID, X and Y properties
      #
      pnt.ID, pnt.X, pnt.Y = string.split(line,",")
      #print pnt.ID, pnt.X, pnt.Y
      if ID == -1:
         ID = pnt.ID
         
      # Add the point to the feature's array of points
      #   If the ID has changed, create a new feature
      #
      #print ID, pnt.ID
      if ID != pnt.ID:
         # Create a new row or feature, in the feature class
         #
         feat = cur.newRow()

         # Set the geometry of the new feature to the array of points
         #
         feat.shape = lineArray

         # Insert the feature
         #
         cur.insertRow(feat)
         lineArray.removeAll()
      lineArray.add(pnt)
      ID = pnt.ID

   # Add the last feature
   #
   feat = cur.newRow()
   feat.shape = lineArray
   cur.insertRow(feat)
      
   lineArray.removeAll()
   del cur
except Exception as e:
   print e.message


I have tried this:

try:
   # Open an insert cursor for the new feature class
   #
   cur = arcpy.InsertCursor(fcname)

   # Create an array and point object needed to create features
   #
   lineArray = arcpy.Array()
   pnt = arcpy.Point()

   # Initialize a variable for keeping track of a feature's ID.
   #
   ID = -1
   for line in coordList: # Open the input file
      # set the point's ID, X and Y properties
      #
      FeatID, pnt.ID, pnt.X, pnt.Y = string.split(line,",")
      print FeatID, pnt.ID, pnt.X, pnt.Y
      if ID == -1:
         ID = pnt.ID
         
      # Add the point to the feature's array of points
      #   If the ID has changed, create a new feature
      #
      #print ID, pnt.ID
      if ID != pnt.ID:
         # Create a new row or feature, in the feature class
         #

         feat = cur.newRow()
         feat.setValue("OW_ID", FeatID)
         # Set the geometry of the new feature to the array of points
         #
         feat.shape = lineArray

         # Insert the feature
         #
         cur.insertRow(feat)
         lineArray.removeAll()
      lineArray.add(pnt)
      ID = pnt.ID

   # Add the last feature
   #
   feat = cur.newRow()
   feat.setValue("OW_ID", FeatID)
   feat.shape = lineArray
   cur.insertRow(feat)
      
   lineArray.removeAll()
   del cur
except Exception as e:
   print e.message


However this does not populate the fcname with the FeatID correctly.

Any help will be greatly appreciated.
0 Kudos
T__WayneWhitley
Honored Contributor
Oh, I see, then you need an ID in the input list...in other words, a identifier to tell when to break your 'point' chain to end entering points and make a poly out of it, then move on to the next 'set' of points.

Is the sample not explicit on how to set up the input list?  So if not clear, your table, string, or otherwise txt file (whatever you have) will look something like:

ID, Xcoord, Ycoord
1, x1, y1
1, x2, y2
1, x3, y3
2, x11, y11
2, x22, y22
2, x33, y33
etc., etc....

That make sense?  So ID 1 defines the 1st poly, ID 2 defines the 2nd poly....and the loop iterates that way, 'pumping' in the new feature when ID changes.

I took that part out in the beginning because I was only demonstrating the part for setting up the coords for a single poly, no ID necessary.  Hope that's a start...

EDIT:  I see now that your original input file contained an ID.  Okay then, the sample script uses this to populate an existing OW_ID field in the output fc.  So just change the name to a named ID field you have set up in your feature class...or don't use it if you don't really need a polygon identifier (OBJECTIDs are auto-populated and you can't fool with those anyway).
0 Kudos
JamesMitchell
Deactivated User
Hello,

As you can see in the code i attached 'FeatID' is the id i would like to assign to the polygons.


I am using 'feat.setValue("OW_ID", FeatID)' to populate the OW_ID field with the FeatID value but it doesnt seem to update the polygons correctly. It is like it is missing the first value.

Thank you
0 Kudos