Shapely:在边缘上的任意点拆分LineString

6
我正在尝试将Shapely的LineString在距离某些其他坐标最近的点处分割。我可以使用project和interpolate获取线路上最接近的点,但是无法在该点处分割线路,因为它不是顶点。
我需要沿边分割线路,而不是捕捉到最近的顶点,以使最近的点成为线路上的新顶点。
以下是我迄今为止所做的:
from shapely.ops import split
from shapely.geometry import Point, LineString

line = LineString([(0, 0), (5,8)])
point = Point(2,3)

# Find coordinate of closest point on line to point
d = line.project(point)
p = line.interpolate(d)
print(p)
# >>> POINT (1.910112359550562 3.056179775280899)

# Split the line at the point
result = split(line, p)
print(result)
# >>> GEOMETRYCOLLECTION (LINESTRING (0 0, 5 8))

谢谢!

1个回答

9

事实证明,我正在寻找的答案已经在文档中概述,使用cut方法:

def cut(line, distance):
    # Cuts a line in two at a distance from its starting point
    if distance <= 0.0 or distance >= line.length:
        return [LineString(line)]
    coords = list(line.coords)
    for i, p in enumerate(coords):
        pd = line.project(Point(p))
        if pd == distance:
            return [
                LineString(coords[:i+1]),
                LineString(coords[i:])]
        if pd > distance:
            cp = line.interpolate(distance)
            return [
                LineString(coords[:i] + [(cp.x, cp.y)]),
                LineString([(cp.x, cp.y)] + coords[i:])]

现在我可以使用“projected distance”来剪切“LineString”:

...
d = line.project(point)
# print(d) 3.6039927920216237

cut(line, d)
# LINESTRING (0 0, 1.910112359550562 3.056179775280899)
# LINESTRING (1.910112359550562 3.056179775280899, 5 8)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接