# Calculate distance between consecutive points

543
4
03-06-2014 03:42 PM
New Contributor
Hi
I wish to calculate the distance between consecutive points in a feature class.
I tried using the following code in the "Pre-Logic VBA Script Code" box in the Field Calculator dialog -

static x0 as double, y0 as double ' Previous location
dim pPoint as IPoint
set pPoint = [Shape]

x = pPoint.X
y = pPoint.Y
d = sqr((x - x0)^2 + (y - y0)^2) ' Distance
x0 = x
y0 = y

but it doesn't work. Does anyone have any suggestions? Thanks for any help anyone can give me.
Tags (2)
4 Replies
by MVP Honored Contributor
Hi
I wish to calculate the distance between consecutive points in a feature class.
I tried using the following code in the "Pre-Logic VBA Script Code" box in the Field Calculator dialog -

static x0 as double, y0 as double ' Previous location
dim pPoint as IPoint
set pPoint = [Shape]

x = pPoint.X
y = pPoint.Y
d = sqr((x - x0)^2 + (y - y0)^2) ' Distance
x0 = x
y0 = y

but it doesn't work. Does anyone have any suggestions? Thanks for any help anyone can give me.

VB Script at 10.0 or later cannot use the DIM statement to create Point variables anymore (or any other variable type other than Variant).  You have to use Python for all geometry field calculations from now on.

Here is my attempt based on an adaptation of the autoincrement calculation.

Parser: Python

Use Codeblock: checked

Pre-Logic Script Codeblock:
`x0 = 0.0y0 = 0.0def distance(x, y): global x0 global y0 if x0 = 0.0 and y0 = 0.0:  x0 = x  y0 = y d = math.sqrt((x - x0)**2 + (y - y0)**2) # Distance x0 = x y0 = y return d`

Expression: distance(!shape.Centroid.X!, !shape.Centroid.Y!)

I am assuming the first point should give a distance of 0, so I set an invalid coordinate that I know will not be in your data and replace that impossible value with the first point value.  If 0,0 is a possible coordinate change the initial x0 and y0 values outside the def to a known invalid point location and change the if condition to match it.
New Contributor
Hi Richard,
great! thanks for that. One slight error the if statement should read - if x0 == 0.0 and y0 = =0.0:
Very much appreciated!
by MVP Honored Contributor
Hi Richard,
great! thanks for that. One slight error the if statement should read - if x0 == 0.0 and y0 = =0.0:
Very much appreciated!

I always forget that.  I am a VB Script guy more than a Python guy and that trips me up all the time.  Anyway, glad you got it working.
by MVP Honored Contributor
Hi Richard,
great! thanks for that. One slight error the if statement should read - if x0 == 0.0 and y0 = =0.0:
Very much appreciated!

I only write VB Script calculations if I don't have to use Python, so when I have to use Python I always forget that = is not == (there is no such thing as == in VB Script).  So I normally make that mistake in all the code examples I write from memory on the Forum that I have not actually run.  In any case, glad it works for what you needed. 