Access individual points in Shapely MultiPoint

Question:

I am working with the Shapely library in Python. I find the intersection of two lines, the return value is given as a MultiPoint object.

How do I deconstruct the object to get the individual points in the intersection?

Here is the code:

from shapely.geometry import LineString, MultiLineString
a = LineString([(0, 1), (0, 2), (1, 1), (2, 0)])
b = LineString([(0, 0), (1, 1), (2, 1), (2, 0)])
x = a.intersection(b)

Output:

print(x) 
MULTIPOINT (1 1, 2 0)

So, in this case, I’d be looking for a way to extract the intersection points (1,1) and (2,0).

Asked By: Chris B

||

Answers:

You can index the resulting MultiPoint:

>>> str(x)
'MULTIPOINT (1 1, 2 0)'
>>> print(len(x))
2
>>> print(x[0].x)
1.0
>>> print(x[0].y)
1.0

If you want a new list with the coordinates, you can use:

>>> [(p.x, p.y) for p in x]
[(1.0, 1.0), (2.0, 0.0)]
Answered By: jjmontes

Use .geoms:

from shapely.geometry import LineString
a = LineString([(0, 1), (0, 2), (1, 1), (2, 0)])
b = LineString([(0, 0), (1, 1), (2, 1), (2, 0)])

multipoint = a.intersection(b)
print(multipoint)
#MULTIPOINT (2 0, 1 1)
points = [p for p in multipoint.geoms]
print(points)
#[<POINT (2 0)>, <POINT (1 1)>]
Answered By: BERA
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.