Using shapely to return co ordinates of multilinestring that intersect

1.5k Views Asked by At

I've generated random streets using Shapely's LineString function using the following code:

class StreetNetwork():

def __init__(self):
    self.street_coords = []
    self.coords = {}

def gen_street_coords(self, length, coordRange):
    min_, max_ = coordRange
    for i in range(length): 
        street = LineString(((randint(min_, max_), randint(min_, max_)),
                  (randint(min_, max_), randint(min_,max_))))
        self.street_coords.append(street)

If I use:

street_network = StreetNetwork() street_network.gen_street_coords(10, [-50, 50])

I get an image like so: Simple

I've been looking at the following question which seems similar. I now want to iterate through my list of street_coords, and split streets into 2 if they cross with another street but I'm finding it difficult to find the co-ordinates of the point of intersection. However, as I am unfamiliar with using Shapely, I am struggling to use the "intersects" function.

1

There are 1 best solutions below

0
On BEST ANSWER

It is rather simple to check intersection of two LineString objects. To avoid getting empty geometries, I suggest to check for intersection first before computing it. Something like this:

from shapely.geometry import LineString, Point

def get_intersections(lines):
    point_intersections = []
    line_intersections = [] #if the lines are equal the intersections is the complete line!
    lines_len = len(lines)
    for i in range(lines_len):
        for j in range(i+1, lines_len): #to avoid computing twice the same intersection we do some index handling
            l1, l2 = lines[i], lines[j]
            if l1.intersects(l2):
                intersection = l1.intersection(l2)
                if isinstance(intersection, LineString):
                    line_intersections.append(intersection)
                elif isinstance(intersection, Point)
                    point_intersections.append(intersection)
                else:
                    raise Exception('What happened?')

    return point_intersections, line_intersections

With the example:

l1 = LineString([(0,0), (1,1)])
l2 = LineString([(0,1), (1,0)])
l3 = LineString([(5,5), (6,6)])
l4 = LineString([(5,5), (6,6)])
my_lines = [l1, l2, l3, l4]
print get_intersections(my_lines)

I got:

[<shapely.geometry.point.Point object at 0x7f24f00a4710>,      
    <shapely.geometry.linestring.LineString object at 0x7f24f00a4750>]