[GIS] Getting and using XY centroids in ArcGIS Field Calculator using Python Code Block

arcgis-10.1arcgis-desktopfield-calculatorpython

I am writing a script to obtain Grid reference but cannot fathom how to get XY centroids without creating new fields (all examples I have found are based on writing XY centroids to field).

Here's my current code and the east / north on top is what I want to achieve:

def getParcel:

    ## east = SHAPE.CENTROID.X
    ## north = SHAPE.CENTROID.Y

    digits = 8 
    # get the 100km-grid
    e100k = math.floor(east/100000)
    n100k = math.floor(north/100000)    
    if e100k<0 or e100k>6 or n100k<0 or n100k>12:
        return ''
    # get numerical equivalents
    l1 = (19-n100k) - (19-n100k)%5 + math.floor((e100k+10)/5)
    l2 = (19-n100k)*5%25 + e100k%5
    if l1 > 7:
        l1 += 1
    if l2 > 7:
        l2 += 1
    # change to integer values
    l1 = int(l1)
    l2 = int(l2)
    # calculate alpha code
    letPair = chr(l1 + (ord('A'))) + chr(l2 + (ord('A')))
    # Strip 100km-grid indices from easting & northing, and reduce precision
    # and change to string value
    e = str(int(math.floor(east%100000 / 10)))
    n = str(int(math.floor(north%100000 / 10)))
    # Pad values if less than 4 digit ref given
    if len(e) < 4:
       e = e.zfill(4)
    if len(n) < 4:
        n = n.zfill(4)
    gridFull = letPair + e + n
        return gridFull

Best Answer

This is easy to do assuming you mean that you want the Centroid coordinates of each parcel currently being calculated. Use !SHAPE.CENTROID.X! and !SHAPE.CENTROID.Y! as parameters to define the expression and then include them in the def as the east and north variables.

If this is somehow trying to use two separate feature classes then you need to use a cursor.

Parser: Python

Use Code Block: Checked

Pre-Logic Script Code:

def getParcel(east, north):

    ## east = SHAPE.CENTROID.X
    ## north = SHAPE.CENTROID.Y

    digits = 8 
    # get the 100km-grid
    e100k = math.floor(east/100000)
    n100k = math.floor(north/100000)    
    if e100k<0 or e100k>6 or n100k<0 or n100k>12:
        return ''
    # get numerical equivalents
    l1 = (19-n100k) - (19-n100k)%5 + math.floor((e100k+10)/5)
    l2 = (19-n100k)*5%25 + e100k%5
    if l1 > 7:
        l1 += 1
    if l2 > 7:
        l2 += 1
    # change to integer values
    l1 = int(l1)
    l2 = int(l2)
    # calculate alpha code
    letPair = chr(l1 + (ord('A'))) + chr(l2 + (ord('A')))
    # Strip 100km-grid indices from easting & northing, and reduce precision
    # and change to string value
    e = str(int(math.floor(east%100000 / 10)))
    n = str(int(math.floor(north%100000 / 10)))
    # Pad values if less than 4 digit ref given
    if len(e) < 4:
       e = e.zfill(4)
    if len(n) < 4:
        n = n.zfill(4)
    gridFull = letPair + e + n
        return gridFull

Expression: getParcel(!SHAPE.CENTROID.X!, !SHAPE.CENTROID.Y!)

Related Question