I have a set of LineStrings which are intersected by other LineStrings and I want to split the LineString into separate segments at these intersection points. I have a solution but I don't think it's the best approach.
Let's say we are dealing with one LineString:
>>> import shapely
>>> from shapely.geometry import *
>>> import geopandas as gpd
>>>
>>> MyLine=LineString([(0,0),(5,0),(10,3)])
>>> MyLine
<shapely.geometry.linestring.LineString object at 0x1277EEB0>
>>>
And 2 lines that intersect this LineString:
>>> IntersectionLines=gpd.GeoSeries([LineString([(2,1.5),(3,-.5)]), LineString([(5,.5),(7,.5)])])
>>> IntersectionLines
0 LINESTRING (2 1.5, 3 -0.5)
1 LINESTRING (5 0.5, 7 0.5)
dtype: object
>>>
I can get the intersection points as follows:
>>> IntPoints=MyLine.intersection(IntersectionLines.unary_union)
>>> IntPointCoords=[x.coords[:][0] for x in IntPoints]
>>> IntPointCoords
[(2.75, 0.0), (5.833333333333333, 0.5)]
>>>
And then I get extract the start and end points and create pairs with these and the intersection points that will be used to form line segments:
>>> StartPoint=MyLine.coords[0]
>>> EndPoint=MyLine.coords[-1]
>>> SplitCoords=[StartPoint]+IntPointCoords+[EndPoint]
>>>
>>> def pair(list):
... for i in range(1, len(list)):
... yield list[i-1], list[i]
...
>>>
>>> SplitSegments=[LineString(p) for p in pair(SplitCoords)]
>>> SplitSegments
[<shapely.geometry.linestring.LineString object at 0x127F7A90>, <shapely.geometry.linestring.LineString object at 0x127F7570>, <shapely.geometry.linestring.LineString object at 0x127F7930>]
>>>
>>> gpd.GeoSeries(SplitSegments)
0 LINESTRING (0 0, 2.75 0)
1 LINESTRING (2.75 0, 5.833333333333333 0.5)
2 LINESTRING (5.833333333333333 0.5, 10 3)
dtype: object
>>>
However, one issue I have with my approach is that I know which intersection point should be joined with the LineString start point and which intersection point should be paired with the LineString end point. This program works if the intersection points are listed along the line in the same order as the start and the ending point. I imagine there would be situations where this would not always be the case? Is there a way to generalize this approach or is there a better approach entirely?