[GIS] Split feature by line in PyQGIS

pyqgispythonqgis

My objects are a polygon and a line. I want to split my polygon according the line. I have used reshapeGeometry and splitGeometry with no success.
ReshapeGeometry returns 0.

Polygon-foo

 foo = QgsGeometry.fromPolygon([[
 QgsPoint(97551.12235755460278597, 285880.81168803840409964),QgsPoint(97560.95150000043213367, 285890.10830000042915344), QgsPoint(97563.86890000011771917, 285895.94270000047981739), QgsPoint(97565.16530000045895576, 285903.0738999992609024), QgsPoint(97565.68680000025779009, 285909.85239999927580357), QgsPoint(97565.80470000021159649, 285911.38529999926686287), QgsPoint(97565.8136999998241663, 285916.55269999988377094), QgsPoint(97565.63819999992847443, 285920.64259999990463257), QgsPoint(97565.52929999958723783, 285923.18290000036358833), QgsPoint(97563.54470000043511391, 285930.62609999999403954), QgsPoint(97561.59989999979734421, 285935.16410000063478947), QgsPoint(97559.03201538244320545, 285944.30644523410592228), QgsPoint(97581.52049999963492155, 285916.17039999924600124), QgsPoint(97607.16040000040084124, 285896.89049999974668026), QgsPoint(97607.82050000037997961, 285860.37030000053346157), QgsPoint(97606.36050000041723251, 285834.48039999976754189), QgsPoint(97576.07029999978840351, 285865.625), QgsPoint(97575.04690000042319298, 285879.3125), QgsPoint(97551.12235755460278597, 285880.81168803840409964)]])

Line-bar

bar = QgsGeometry.fromPolyline([
QgsPoint(97551.11000000033527613, 285880.80000000074505806), QgsPoint(97560.95150000043213367, 285890.10830000042915344), QgsPoint(97563.86890000011771917, 285895.94270000047981739), QgsPoint(97565.16530000045895576, 285903.0738999992609024), QgsPoint(97565.68680000025779009, 285909.85239999927580357), QgsPoint(97565.80470000021159649, 285911.38529999926686287), QgsPoint(97565.8136999998241663, 285916.55269999988377094), QgsPoint(97565.63819999992847443, 285920.64259999990463257), QgsPoint(97565.52929999958723783, 285923.18290000036358833), QgsPoint(97563.54470000043511391, 285930.62609999999403954), QgsPoint(97561.59989999979734421, 285935.16410000063478947), QgsPoint(97559.03199999965727329, 285944.30650000087916851)])

Opertation

    p=foo
    p1=foo
    t=p.geometry().reshapeGeometry(bar.geometry().asPolyline())
    print t
    print p.geometry().exportToGeoJSON()
    print p1.geometry().exportToGeoJSON()
    print p.geometry().area()
    print p.geometry().area()

Best Answer

A simple way would be using The polygon-line intersection tool from the SAGA toolbox.

This would work:

import processing
polys = QgsVectorLayer(r"C:\PyQGIS_Test\polys.shp", 'poly', 'ogr')
lines = QgsVectorLayer(r"C:\PyQGIS_Test\lines.shp", 'lines', 'ogr')
output = r"C:\PyQGIS_Test\splitPolys.shp"
processing.runalg("saga:polygonlineintersection",polys,lines,output)

Input:
enter image description here

Output:
enter image description here