helenak

modify a python code for centroid X Y coordinate (latitude and longitude)

Discussion created by helenak on Apr 28, 2012
Hello,

I am using ArcGIS 9.3 and PythonWin 2.5.

Here I have a python code to generate centroid latitude and longitude for polygon shapefiles.
It ran well for a single shapefile but exception occured for multiple ones in the same folder.
Therefore, please kindly advise how to modify the code for:

1. multiple polygon shape files in the same folder
2. to generate X and Y coordinate  (latitude and longitude) in the unit of degree decimal point.
   (The projection is Behrmann, and the current X and Y coordinates is in the unit of meter.)
3. to show the centroid (point) in the result shapefile as well (Currently only the original polygon are presented)

Thanks a lot

Code
#Tool Name: Calculate PolyCentroid
#Source Name: PolyCentroid.py
#Version: ArcGIS 9.1 date: 10/28/05
#Author: Anthony Palmer, U.S. Army Corps of Engineers
#
#This tool adds two fields ("Xcoord" and "Ycoord") to a polygon feature class.  Then
#finds the centroids for each polygon within the feature class, extracts the x and y
#values, and updates the appropriate fields.
#
#imports
#
from win32com.client import Dispatch
import sys
GP = Dispatch("esriGeoprocessing.GpDispatch.1")
GP.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
#
# Get the input shapefile name
in_shapefile = sys.argv[1] #GP.getParameterAsText(0)
#
#Add the Xcoord, Ycoord, RC_ID fields
desc = GP.Describe(in_shapefile)
shapeField = desc.ShapeFieldName
if desc.ShapeType == "Polygon":
    type = "poly"
    try:
        GP.AddField(in_shapefile,"Xcoord","double")
        GP.AddField(in_shapefile,"Ycoord","double")
        GP.AddMessage("Added fields to the table.")
    except:
        GP.AddMessage("Updating all fields...")
else:
    GP.AddMessage("Input must be a polygon shapefile.")
    raise("Error")
#
#Update the Xcoord and Ycoord Fields
rows = GP.UpdateCursor(in_shapefile)
row = rows.next()
GP.AddMessage("Calculating Values...")
while row:                       
    ashape = row.shape
    aCentroid = ashape.Centroid
    aXcoord = aCentroid.split(" ") [0]
    aYcoord = aCentroid.split(" ") [1]
    row.SetValue("Xcoord", aXcoord)
    row.SetValue("Ycoord", aYcoord)
    rows.UpdateRow(row)
    row = rows.next()                # Get the next feature and repeat
del rows
#
del GP

Outcomes