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
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.
-
In shapely 2.0.0:
TypeError: 'GeometryCollection' object is not iterable
swiss_knight– swiss_knight2023年02月03日 14:54:40 +00:00Commented Feb 3, 2023 at 14:54 -
3In Shapely 2+ you must access
A.geoms
Damien– Damien2023年05月10日 15:14:02 +00:00Commented May 10, 2023 at 15:14 -
Damien, you are right, A.geoms is the answer. I edit my answer.Eric H.– Eric H.2023年05月12日 05:15:39 +00:00Commented May 12, 2023 at 5:15
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])