在它以匀称的方式穿过多边形的每个点处拆分线串

Split a linestring at each point it crosses a polygon in shapely

我有一个跨越各种多边形的线串,存储为 GeoJsons。我想将线分割成每个多边形区域内的各个部分。然而,我还没有能够做到这一点。这是我目前拥有的可重现示例:

from shapely.geometry import Point, LineString, Polygon
from shapely.ops import split
from matplotlib import pyplot as plt

poly = {
    'type': "Feature",
    'geometry': {
        "type": "Polygon",
        "coordinates": ([(2,2),(2,4),(4,4),(4,2)]),
    },
    'properties': {
        'id': 'A'
    }
}

line = {
    'type': "Feature",
    'geometry': {
        "type": "Linestring",
        "coordinates": ([(3,3),(5,1)]),
    },
    'properties': {
        'id': 'A'
    }
}

poly = Polygon(poly['geometry']['coordinates'])
line = LineString(line['geometry']['coordinates'])

x,y = poly.exterior.xy
x2,y2 = line.coords

plt.plot(x, y, x2, y2)
plt.show()

此代码生成以下正方形多边形,其中有一条线串穿过它:

然后我尝试通过多边形分割线,如下所示:

new_lines = split(line, poly)

但我得到以下似乎不正确的输出:

GEOMETRYCOLLECTION (LINESTRING (3 3, 4 2), LINESTRING (4 2, 5 1))

我期待三条线,一条存在于正方形多边形内,然后两条分别存在于多边形外。

看起来 split 正在按您预期的那样工作,但是线的坐标以误导的方式绘制 - 应该使用 .xy 来获取线 xsys多边形:

from shapely.geometry import Point, LineString, Polygon
from shapely.ops import split
from matplotlib import pyplot as plt

poly = Polygon([(2,2),(2,4),(4,4),(4,2)])
original_line = LineString([(3,3),(5,1)])
line = LineString([(3,1), (3,5)])
x, y = poly.exterior.xy
x2, y2 = line.xy
x3, y3 = original_line.xy

plt.plot(x, y, x2, y2)
plt.show()

plt.plot(x, y, x3, y3)
plt.show()

image with original coords

image with expected coords

>>> print(split(line, poly))
GEOMETRYCOLLECTION (LINESTRING (3 1, 3 2), LINESTRING (3 2, 3 4), LINESTRING (3 4, 3 5))