[GIS] Getting line geometry out of two points using QGIS

geometrypyqgispyqgis-3qgisqgis-3

I have one input point layer and out of that, I want to create an output LINE vector layer.

For each feature in my output line vector layer, I define a geometry which takes 2 point geometries. Figuratively speaking, imagine a line which connects both points -> this should be the line feature I want to add to my output layer!

I have tried it like this:

newEdge = QgsFeature(outFields)
geom = QgsGeometry.fromPolyline([geomFrom.asPoint(),geomTo.asPoint()]) # The error happens here!
newEdge.setGeometry(geom)

This had worked for me in QGIS2.x, but with QGIS3, I get the following error:

Traceback (most recent call last):
File "", line 194, in processAlgorithm
TypeError: index 0 has type 'QgsPointXY' but 'QgsPoint' is expected

Any suggestions?

Best Answer

Try the following

points = []
pt = QgsPointXY(0,0)
points.append(pt)
pt = QgsPointXY(1,1)
points.append(pt) 
fields = some_layer.dataProvider().fields()
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPolylineXY(points))
feature.setFields(fields)
feature.setAttribute('id', 1)
some_layer.addFeature(feature)

I do not know the reason but pyqgis 3 works only with QgsPointXY and prefers creating polyline by QgsGeometry.fromPolylineXY(). I discovered this case when like you adapted some code from Qgis 2.18 - Python 2.7 to Qgis 3.2 - Python 3.6

Related Question