Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I'm new to Python and I'm having some dificulties. I want to create a simple layer with a line in the console of QGIS with Python. How can I do that?

share|improve this question
    
Are you trying to do something different than what you asked in another question? gis.stackexchange.com/questions/60007/… –  user3461 May 9 '13 at 14:28
    
Yes because I whant to make an action with python –  user1573901 May 9 '13 at 14:33

1 Answer 1

You must first understand how PyQGIS handles geometry (Geometry Handling)

The most important element is the point:

QgsPoint(x,y)

and a line or a segment of line are composed of two points:

QgsGeometry.fromPolyline([QgsPoint(x1,y1),QgsPoint(x2,y2)]));

So to construct a line:

line_start = QgsPoint(50,50)
line_end = QgsPoint(100,150)
line = QgsGeometry.fromPolyline([line_start,line_end])

and with a memory layer (geometry only, without the attributes):

# 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])

the result is:

enter image description here

with 3 points, just add it as a new feature:

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])

and the result is:

enter image description here

And with a for loop you can create a line with many segments:

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.