2

I have a shapefile of lines. I want the angle of every line calculated in a field.

I am using the script below in arcmap, but when it encounters a line that is horizontal, it stops calculating any remaining values and gives the following error:

The field is not nullable.

I searched for answers to similar questions, not getting too far with them.

Where I originally found this code: https://geonet.esri.com/thread/20473#21719

Pre-logic Script code:

import math  
def GetAzimuthPolyline(shape):  
 radian = math.atan((shape.lastpoint.x - shape.firstpoint.x)/(shape.lastpoint.y - shape.firstpoint.y))  
 degrees = radian * 180 / math.pi  
 return degrees  

Expression:

GetAzimuthPolyline( !Shape!) 
1
  • Is there any blank record(row) in the featureclass/shapefile?
    – Learner
    Commented Dec 10, 2015 at 6:19

3 Answers 3

2

To avoid a divide by zero error I would try changing:

import math  
def GetAzimuthPolyline(shape):  
 radian = math.atan((shape.lastpoint.x - shape.firstpoint.x)/(shape.lastpoint.y - shape.firstpoint.y))  
 degrees = radian * 180 / math.pi  
 return degrees

to:

import math  
def GetAzimuthPolyline(shape):  
  if shape.lastpoint.y - shape.firstpoint.y != 0:
    radian = math.atan((shape.lastpoint.x - shape.firstpoint.x)/(shape.lastpoint.y - shape.firstpoint.y))  
    degrees = radian * 180 / math.pi  
    return degrees
  else:
    return 90
0
2

there is no "null" field with shapefile because it uses dbf table. see here

Apart from that, you could adapt your code for horizontal lines

import math  
    def GetOrientation(shape): 
     if  (shape.lastpoint.y == shape.firstpoint.y):
       degree = 90
     else:  
       radian = math.atan((shape.lastpoint.x - shape.firstpoint.x)/(shape.lastpoint.y - shape.firstpoint.y))  
       degrees = radian * 180 / math.pi  
     return degrees  
0

This will calculate classic type direction, i.e. counterclockwise from East =positive.

import math
def getAngle(shp):
 p1=shp.firstPoint;p2=shp.lastPoint
 dX=p2.X-p1.X;dY=p2.Y-p1.Y
 try:
  z=math.atan(-dY/dX)
 except:
  z=math.pi/2 
  if dY>0: z=-math.pi/2
 z=z*180/math.pi
 if dX<0:z+=180
 z=-((z+180)%360-180)
 return z

To call it use:

getAngle( !Shape! )

OUTPUT:

enter image description here

As it is frequently the case, the idea borrowed from one of the old posts of @whuber, I struggle to locate it though.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.