Monday 27 February 2017

qgis - Split a feature when intersecting with a feature of another layer using PyQGIS/Python?


I have a buffer layer (green polygon) which I want to split to two polygons whenever it crosses a barrier (blue line). I have been trying to use "splitGeometry" method, but I just can't get it to work. My code so far is this :


while ldbuffprovider.nextFeature(feat):
while barprovider.nextFeature(feat2):
if feat.geometry().intersects(feat2.geometry()):
intersection = feat.geometry().intersection(feat2.geometry())

result, newGeometries, topoTestPoints=feat.geometry().splitGeometry(intersection.asPolyline(),True)

Which returns 1 for result( error) and an empty list for newGeometries. Any help is greatly appreciated.


enter image description here



Answer



You can use the reshapeGeometry function of the QgsGeometry object for this, which cuts a polygon along its intersection with a line.


The following will intersect the buffer polygons with the lines, and add the split polygon features to a memory layer (QGIS 2.0 syntax):


# Get the dataProvider objects for the layers called 'line' and 'buffer'
linepr = QgsMapLayerRegistry.instance().mapLayersByName('line')[0].dataProvider()
bufferpr = QgsMapLayerRegistry.instance().mapLayersByName('buffer')[0].dataProvider()


# Create a memory layer to store the result
resultl = QgsVectorLayer("Polygon", "result", "memory")
resultpr = resultl.dataProvider()
QgsMapLayerRegistry.instance().addMapLayer(resultl)


for feature in bufferpr.getFeatures():
# Save the original geometry
geometry = QgsGeometry.fromPolygon(feature.geometry().asPolygon())

for line in linepr.getFeatures():
# Intersect the polygon with the line. If they intersect, the feature will contain one half of the split
t = feature.geometry().reshapeGeometry(line.geometry().asPolyline())
if (t==0):
# Create a new feature to hold the other half of the split
diff = QgsFeature()
# Calculate the difference between the original geometry and the first half of the split
diff.setGeometry( geometry.difference(feature.geometry()))
# Add the two halves of the split to the memory layer
resultpr.addFeatures([feature])

resultpr.addFeatures([diff])


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...