I am trying to follow the python code below (Finding middle point (midpoint) of line in QGIS?) to create midpoints of line segments in QGIS 1.8. I am receiving errors executing the code. Unfortunately, I have no background in Python.
>>> def pair(list):
... '''Iterate over pairs in a list '''
... for i in range(1, len(list)):
File "<input>", line 3
**for i in range(1, len(list)):**
^
IndentationError: unexpected indent**
another error:
>>> yield list[i-1], list[i]
**File "<input>", line 1
yield list[i-1], list[i]
^
IndentationError: unexpected indent**
and finally
**Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'mylayer' is not defined**
Pyhton code:
def mid(pt1, pt2):
x = (pt1.x() + pt2.x())/2
y = (pt1.y() + pt2.y())/2
return QgsPoint(x,y)
def pair(list):
'''Iterate over pairs in a list '''
for i in range(1, len(list)):
yield list[i-1], list[i]
def create_geometry(point,pr):
# create geometry record
seg = QgsFeature()
seg.setGeometry(QgsGeometry.fromPoint(point))
pr.addFeatures( [seg] )
# memory layer
pt_layer = QgsVectorLayer("Point", "midpoint", "memory")
pr = pt_layer.dataProvider()
for elem in mylayer.selectedFeatures():
line = elem.geometry()
for seg_start, seg_end in pair(line.asPolyline()):
line_start = QgsPoint(seg_start)
line_end = QgsPoint(seg_end)
# midpoint
midpt= mid(line_start, line_end)
# add midpoint point to layer
create_geometry(midpt,pr)
pt_layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([pt_layer])
'''Iterate over pairs in a list '''
andfor i in range(1, len(list)):
with the same indentationIndentationError
for each improperly indented lines.