Distance calculations in the field calculator

4049
0
08-22-2017 07:13 AM

Distance calculations in the field calculator

ReferenceCalculate Distance.                   

Date: 2017-08-22

Cumulative Distance

If you want distance from the first point in a data table to every other point in sequence,  then use cumulative distance function below.

Do the following:

  • select Python parser
  • toogle on Show  code block
  • paste the following in the Pre-logic Script Code block
  • and the last piece in the expression box

Pre-logic Script Code:

""" input shape field: returns cumulative distance between points
dist_cumu(!Shape!)    #enter into the expression box"""
x0 = 0.0;  y0 = 0.0;  distance = 0.0
def dist_cumu(shape):
    global x0;  global y0;  global distance
    x = shape.firstpoint.X;  y = shape.firstpoint.Y
    if x0 == 0.0 and y0 == 0.0:
        x0 = x; y0 = y
    distance += math.sqrt((x - x0)**2 + (y - y0)**2)
    x0 = x;  y0 = y
    return distance
‍‍‍‍‍‍‍‍‍‍‍

calculation field =

dist_cumu(!Shape!)

NOTES:

If nothing is selected in the table, then the calculation will proceed from the first point and the cumulative distances will be done in sequential order.  If you have 3 or more points selected, then it will calculate the values with just the selection.  No cannot rearrange the order...write a script, there is only so much you can do in the field calculator.

-----------------------------------------------------------------------------------------------------------------------------------------

Inter-point distance

For distances between sequential point pairs (not cumulative), use the dist_between function.

Do the following:

  • select Python parser
  • toogle on Show  code block
  • paste the following in the Pre-logic Script Code block
  • and the last piece in the expression box

Pre-logic Script Code:

""" input shape field: returns the distance between points and its center
dist_between(!Shape!)    #enter into the expression box"""
x0 = 0.0;  y0 = 0.0
def dist_between(shape):
    global x0;  global y0
    x = shape.firstpoint.X; y = shape.firstpoint.Y
    if x0 == 0.0 and y0 == 0.0:
        x0 = x; y0 = y 
    distance = math.sqrt((x - x0)**2 + (y - y0)**2)
    x0 = x;  y0 = y
    return distance
‍‍‍‍‍‍‍‍‍‍‍

calculation field =

dist_between(!Shape!)

Notes:

Make sure you have projected data and a double field or nothing will make sense.  The same comments apply to calculations using selections as mentioned above.

Version history
Last update:
‎12-12-2021 03:44 AM
Updated by: