求距离 起点/终点 某距离点

from shapely.geometry import MultiPoint, LineString

# LineString 的 WKT 字符串示例
wkt_linestring = "LINESTRING (10 40, 40 30, 20 20, 30 10)"

# 解析 LineString
linestring = wkt.loads(wkt_linestring)
print(type(linestring.coords))
print(linestring.interpolate(0.5,normalized=True))
print(linestring.interpolate(10))
print(linestring.interpolate(-10))
print(linestring.interpolate(1.5,normalized=True))
print(linestring.interpolate(-1.5,normalized=True))

interpolate - normalized=Flase

此时计算的是 该线上 距离起始点(10,40)  指定单位长度 的点,如上代码是10个单位长度

interpolate - normalized=True

此时计算的是 该线上距离起始点 线总长度*参数 的点,如

print(linestring.interpolate(0.5,normalized=True))
就是计算这条线的中点位置,也就是距离起点一半线长度的位置

interpolate - 负数

就是把终点作为起点,比如

print(linestring.interpolate(-10))

是求距离(30,10)10个单位长度的点

这里interpolate的原理,会放到下个文章回顾(插值法)

判断点是否在线上

from shapely.geometry import Point, LineString

def is_point_on_line(line: LineString, point: Point, tolerance: float = 1e-6) -> bool:
    """判断点是否在线上(支持容差)"""
    return line.distance(point) <= tolerance

# 示例
line = LineString([(0, 0), (1, 1), (2, 2)])
point = Point(1, 1.000001)  # 微小误差

print(is_point_on_line(line, point))  # 输出: True(在容差范围内)

tolerance代表支持的误差范围

计算点到线的距离 及 最近点坐标

from shapely.geometry import Point, LineString
from shapely.ops import nearest_points

def calculate_distance_and_nearest_point(line: LineString, point: Point) -> tuple:
    """计算点到线的距离及线上最近点坐标"""
    distance = line.distance(point)
    nearest_point = nearest_points(point, line)[1]
    return distance, (nearest_point.x, nearest_point.y)

# 示例
line = LineString([(0, 0), (1, 1), (2, 2)])
point = Point(0.5, 1.5)

distance, nearest_coords = calculate_distance_and_nearest_point(line, point)
print(f"点到线的距离: {distance:.4f}")
print(f"线上最近点坐标: {nearest_coords}")

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐