Skip to content

Instantly share code, notes, and snippets.

@jklymak
Last active March 30, 2022 13:19
Show Gist options
  • Save jklymak/574b3396d4eb30ac6592ccb2def7350a to your computer and use it in GitHub Desktop.
Save jklymak/574b3396d4eb30ac6592ccb2def7350a to your computer and use it in GitHub Desktop.
Distance along a line
"""
Use https://github.com/jklymak/waypoint_distance instead!
"""
def get_xy(ds, lat0, lon0):
x = (ds.longitude - lon0) * np.cos(np.deg2rad(lat0)) * 60 * 1.852
y = (ds.latitude - lat0) * 60 * 1.852
ds['x'] = x
ds.x.attrs['units'] = f'km east of {lon0}'
ds['y'] = y
ds.y.attrs['units'] = f'km north of {lat0}'
return ds
def dist(x1,y1, x2,y2, x3,y3): # x3,y3 is the point
px = x2-x1
py = y2-y1
dsq = px*px + py*py
u = ((x3 - x1) * px + (y3 - y1) * py) / dsq
if u > 1:
u = 1
elif u < 0:
u = 0
x = x1 + u * px
y = y1 + u * py
dx = x - x3
dy = y - y3
dist = np.sqrt(dx*dx + dy*dy)
return dist
def get_alongx(wps, x, y):
distline = np.zeros(len(wps)-1)
for j in range(1, len(wps)-1):
distline[j] = np.sqrt((wps[j-1][0] - wps[j][0])**2 + (wps[j][1] - wps[j-1][1])**2)
ind = np.zeros(len(x))
for j in range(len(x)):
thedist = np.Inf
for i in range(len(waypoints)-1):
dd = dist(wps[i][0], wps[i][1], wps[i+1][0], wps[i+1][1], x[j], y[j])
if dd < thedist:
thedist = dd
ind[j] = i
alongx = x * 0.
for i in range(len(x)):
# get the distance along the line....
indd = int(ind[i])
x0 = wps[indd][0]
x1 = wps[indd+1][0]
y0 = wps[indd][1]
y1 = wps[indd+1][1]
xp = x[i] - x0
yp = y[i] - y0
dot = xp * (x1 - x0) + yp * (y1 - y0)
dot = dot / np.sqrt((x1 - x0)**2 + (y1 - y0)**2)
alongx[i] = dot + distline[indd]
return alongx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment