Mainland
Mainland

Reputation: 4564

Find a point on a line at a specific distance by X-axis from the first point

I have a line with (x1,y1) and (x2,y2) endpoints. My task is to find my points in between. I want to find a point (xnew,ynew) from (x1,y1) such that xnew is 0.1 units distance from x1. How do I find ynew here?

My code:

# I know how to find the mid point
def find_line_mid(x1,y1,x2,y2)
    xnew = (x1+x2)/2
    ynew = (y1+y2)/2  
    return xnew,ynew
# My attempt
# We know that slope along the line is constant. We use it here
sl = (y2-y1)/(x2-x1)
xnew = x1+0.1
ynew = sl*(xnew)+y1 # from y=mx+c

is this a correct approach?

How can I find a point at a specific distance from the first point?

enter image description here

Upvotes: 2

Views: 1019

Answers (2)

Georgy
Georgy

Reputation: 13687

Using Shapely, you could construct a vertical line at the specified distance from the given point (x1, y1), and find the intersection of both lines:

from shapely.geometry import LineString

x1, y1 = 0, 2
x2, y2 = 2, 0
x_dist = 0.5

line = LineString([(x1, y1), (x2, y2)])
x_new = x1 + x_dist
vertical = LineString([(x_new, y1), (x_new, y2)])
new_point = line.intersection(vertical)
print(new_point)
# POINT (0.5 1.5)
print(new_point.y)
# 1.5

enter image description here


Also, worth noting that Shapely actually provides interpolate method with similar functionality which is to find a point at the specified distance along a line:

line = LineString([(0, 0), (5, 5)])
distance = 2
new_point = line.interpolate(distance)
print(new_point)
# POINT (1.414213562373095 1.414213562373095)

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 148880

If 3 points with resp. coordinates (x1, y1), (x2, y2) and (xnew, ynew) are aligned, and x1 != x2, then you have the following relation:

ynew - y1 == (xnew - x1) * (y2 - y1) / (x2 - x1)

It immediately gives:

ynew = y1 + (xnew - x1) * (y2 - y1) / (x2 - x1)

Upvotes: 2

Related Questions