3

I am using 'intersection' function from Shapely to find junctions of a road network. As i found, intersection returns GeometryCollection. In my case it could be Point, LineString or perhaps MultiLineString. I want to segregate these objects based on their geometry. I only want Point objects for further use. I found similar post here

It suggests to use as.GeometryCollection however, in my case it gives:
p = l1.intersection(l2).asGeometryCollection()
AttributeError: 'GeometryCollection' object has no attribute
'asGeometryCollection'

here is the sample code: (I expect to get points in junctions[])

with open('./lines.geojson') as f:
routes = json.load(f)
junctions =[]
for i in range(len(routes['features'])-1): 
 j =i+1 
 while (j < len(routes['features'])):
 l1 = LineString(routes['features'][i]['geometry']['coordinates'])
 l2 = LineString(routes['features'][j]['geometry']['coordinates'])
 p = l1.intersection(l2).asGeometryCollection()
 junctions.append(p[0]) 
 j = j+1 
asked Mar 2, 2016 at 0:30

2 Answers 2

4

If an object A is a GeometryCollection, its content can be accessed using :

for geom in A.geoms:
 ...

except if A is a GEOMETRYCOLLECTION EMPTY.

answered Jan 19, 2021 at 14:19
3
  • In shapely 2.0.0: TypeError: 'GeometryCollection' object is not iterable Commented Feb 3, 2023 at 14:54
  • 3
    In Shapely 2+ you must access A.geoms Commented May 10, 2023 at 15:14
  • Damien, you are right, A.geoms is the answer. I edit my answer. Commented May 12, 2023 at 5:15
2

You've confused the QGIS and Shapely libraries. The code in the similar post doesn't apply to Shapely.

In your case, p = l1.intersection(l2) returns an instance of Shapely's GeometryCollection. p[0] is the first part of that collection. All you need is:

p = l1.intersection(l2)
junctions.append(p[0])
answered Mar 2, 2016 at 4:03
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.