I'm getting some geometries via intersecting lines by polygons (somewhat blindly - I don't really know if intersection exists and actually I don't need to know) using python and QGIS API: some_line.intersection(some_polygon).

To my mind I may get several types of geometry:

  1. None (if there is no intersection).
  2. Point
  3. Linestring
  4. Multilinestring
  5. Geometry collections (when there are several points and/or lines)

but the geometry I need in the end is a Linestring (Polyline) or several Linestrings (not MultilineStrings). I can identify geometry type using wkbType(). It returns integer, and this integer corresponds to this order.

How can I split MultilineStrings and Geometry collections and get the parts they are consist of (preferably using QGIS API)?

I wasn't able to find such function in QGIS API, maybe just missed it? There is also GetGeometryRef() function in OGR that I believe could help me, but I can't figure out how to implement it in my case.

1 Answer 1


One of the developers showed me how to do it. It is quite easy. One need to export geometry to GeometryCollection like: i = line.intersection(polygon).asGeometryCollection() and then pick items form it (like for n in i: or i[0]).

Here is an example:

>>>poly = QgsGeometry.fromPolygon([  [ QgsPoint(1,3), QgsPoint(4,3), QgsPoint(4,1), QgsPoint(3,1), QgsPoint(3,2), QgsPoint(2,2), QgsPoint(2,1), QgsPoint(1,1), QgsPoint(1,3) ] ])
>>>line = QgsGeometry.fromPolyline( [ QgsPoint(2,1), QgsPoint(7,2) ] )
>>>i = line.intersection(poly).asGeometryCollection()
POINT(2.000000 1.000000)
LINESTRING(3.000000 1.200000, 4.000000 1.400000)

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.