A while ago, I wrote this Python function that returns 'E', 'NE', 'N', etc. based on the overall direction of a line geometry (i.e. the direction from its starting coordinates to its ending coordinates).
def determine_arc_bearing(line_geom):
''' Determines the cardinal direction of a single arc, determined from its
two endpoints. The angle is determined by the atan2() function, and
after some numeric manipulation is then used to select the correct
cardinal direction from an ordered list of possibilities. '''
from math import atan2, degrees, floor
x1 = line_geom.firstPoint.X
y1 = line_geom.firstPoint.Y
x2 = line_geom.lastPoint.X
y2 = line_geom.lastPoint.Y
xdiff = x2 - x1
ydiff = y2 - y1
angle = degrees(atan2(ydiff, xdiff))
index = int(floor(((angle + 22.5) % 360) / 45))
cardinal_dirs = ('E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE') # Order here is critical
bearing = cardinal_dirs[index]
return bearing
You can adapt the code after the coordinate calculations to suit your own needs. The key part are the 3 lines at the end that calculate index
, cardinal_dirs
and bearing
. You could use a stripped-down version of this function that accepts your NEAR_ANGLE field as the argument in your pre-logic script code:
def determine_heading(angle):
from math import floor
index = int(floor(((angle + 22.5) % 360) / 45))
cardinal_dirs = ('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW') # Order here is critical
bearing = cardinal_dirs[index]
return bearing
And then the expressions for actually calculating HEADING =
determine_heading(!NEAR_ANGLE!)