Shapely:沿着边缘的任意点分割LineString

时间:2018-05-14 14:03:10

标签: python shapely geopandas

我正在尝试将Shapely LineString 分割到最近的某个坐标点。我可以使用projectinterpolate获取该行的最近点,但由于它不是顶点,我无法在此处分割线。

我需要沿着边缘分割线,而不是捕捉到最近的顶点,以便最近的点成为线上的新顶点。

这是我到目前为止所做的:

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 个答案:

答案 0 :(得分:4)

事实证明我所寻找的答案在documentation中列为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:])]

现在我可以使用project距离来剪切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)