Anda harus terlebih dahulu memahami bagaimana PyQGIS menangani geometri ( Penanganan Geometri )
Elemen yang paling penting adalah intinya:
QgsPoint (x, y)
dan garis atau segmen garis terdiri dari dua titik:
QgsGeometry.fromPolyline ([QgsPoint (x1, y1), QgsPoint (x2, y2)]));
Jadi untuk membangun garis:
line_start = QgsPoint(50,50)
line_end = QgsPoint(100,150)
line = QgsGeometry.fromPolyline([line_start,line_end])
dan dengan lapisan memori (hanya geometri, tanpa atribut):
# create a new memory layer
v_layer = QgsVectorLayer("LineString", "line", "memory")
pr = v_layer.dataProvider()
# create a new feature
seg = QgsFeature()
# add the geometry to the feature,
seg.setGeometry(QgsGeometry.fromPolyline([line_start, line_end]))
# ...it was here that you can add attributes, after having defined....
# add the geometry to the layer
pr.addFeatures( [ seg ] )
# update extent of the layer (not necessary)
v_layer.updateExtents()
# show the line
QgsMapLayerRegistry.instance().addMapLayers([v_layer])
hasilnya adalah:
dengan 3 poin, tambahkan saja sebagai fitur baru:
newpoint = QgsPoint(143,125)
v_layer = QgsVectorLayer("LineString", "line_3pt", "memory")
pr = v_layer.dataProvider()
seg = QgsFeature()
seg.setGeometry(QgsGeometry.fromPolyline([line_start, line_end]))
# new feature: line from line_end to newpoint
seg = QgsFeature()
seg.setGeometry(QgsGeometry.fromPolyline([line_end, newpoint]))
pr.addFeatures( [ seg ] )
v_layer.updateExtents()
# add the line to
QgsMapLayerRegistry.instance().addMapLayers([v_layer])
dan hasilnya adalah:
Dan dengan for for Anda dapat membuat garis dengan banyak segmen: