2

I create a new qgis file and run the following code.

# create a line
line = QgsFeature()
line.setGeometry(QgsGeometry.fromPolyline([QgsPoint(50,50), QgsPoint(10,10)]))

# create a layer
layer =  QgsVectorLayer('LineString', 'my line' , 'memory')
dp = layer.dataProvider() 
dp.addFeatures([line])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])

# get the line feature
layer = QgsMapLayerRegistry.instance().mapLayersByName('my line')[0]
fs = layer.getFeatures()
f = fs.next()

print 'before split', f.geometry().length()

# split the line
points = [QgsPoint(50, 10), QgsPoint(10, 50)]
result, new_geoms, test_points = f.geometry().splitGeometry(points, True) 

print 'after split', f.geometry().length()

f.setGeometry(new_geoms[0])

# necessary?
layer.updateFeature(f) 
layer.updateExtents()

The code creates a line and splits it. The length of the line before and after split are 56.5685424949 and 28.2842712475. However, the endpoints of the line are still (50,50) and (10,10). It was not splitted.

enter image description here

enter image description here

1 Answer 1

2

Look at splitGeometry returns one part of the splitted line, instead of two or [Python] splitGeometry

The line is splitted into two parts. Part one is still f (but changed). The second (new) geometry is in new_geoms:

# original line
print f.geometry().exportToGeoJSON()
"type": "LineString", "coordinates": [ [50, 50], [10, 10] ] }
# splitting
result, new_geoms, test_points = f.geometry().splitGeometry(points, True)
# part 1
print f.geometry().exportToGeoJSON()
{ "type": "LineString", "coordinates": [ [50, 50], [30, 30] ] }   
# part 2
for geom in new_geoms:
     print geom.exportToGeoJSON()
{ "type": "LineString", "coordinates": [ [30, 30], [10, 10] ] }
1
  • Thank you for illustrating how splitGeometry() work by using exportToGeoJSON(). The latter method will be very useful for me. Anyway, after your code splits the line (i.e., in #part1), the geometry of f is changed. I believe my code also changed the geometry. But QGIS still display the same line after splitGeometry() is called. I even assign the new geometry to f but QGIS still shows the old line.
    – wannik
    Sep 20, 2014 at 2:34

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.