Skip to content

Instantly share code, notes, and snippets.

@yingminc
Last active July 13, 2017 05:18
Show Gist options
  • Save yingminc/e233474a1140d4a3801a59197d7de8f2 to your computer and use it in GitHub Desktop.
Save yingminc/e233474a1140d4a3801a59197d7de8f2 to your computer and use it in GitHub Desktop.
get the middle points of lines in Qgis
from qgis.core import *
import qgis.utils
def midpair(plist):
'''Iterate over pairs in a list '''
x=[]
y=[]
for c in plist:
x.append(c[0])
y.append(c[1])
if len(plist) ==2:
mx = (max(x)+min(x))/2
my = (max(y)+min(y))/2
elif len(plist) % 2 == 1:
mx = x[(len(plist)+1)/2]
my = y[(len(plist)+1)/2]
else:
mx = (x[len(plist)/2] + x[(len(plist)/2)+1])/2
my = (y[len(plist)/2] + y[(len(plist)/2)+1])/2
return QgsPoint(mx, my)
def create_geometry(point,pr):
# create geometry record
seg = QgsFeature()
#seg.setAttribute([name])
seg.setGeometry(QgsGeometry.fromPoint(point))
pr.addFeatures( [seg] )
s12p = QgsVectorLayer("Point", "s12-16midpoint_2", "memory")
pr = s12p.dataProvider()
pr.addAttributes([QgsField('combo')])
s12 = qgis.utils.iface.activeLayer()
iter = s12.getFeatures()
c = 0
for f in iter:
g= f.geometry()
m_p = midpair(g.asPolyline())
#g.asPolyline() return a list of points in the line;
#could be more than 2 points(when the line is curvy)
create_geometry(m_p,pr)
s12p.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([s12p])
print ('done')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment