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  

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.

3
  • In shapely 2.0.0: TypeError: 'GeometryCollection' object is not iterable Commented Feb 3, 2023 at 14:54
  • 2
    In Shapely 2+ you must access A.geoms
    – Damien
    Commented May 10, 2023 at 15:14
  • Damien, you are right, A.geoms is the answer. I edit my answer.
    – Eric H.
    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])
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.