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 am trying to locate the coordinates of the middle point of a line feature in QGIS. I tried searching online but can't seem to find an easy way to do this.

share|improve this question
    
looks like you can do it in GRASS, see link lists.osgeo.org/pipermail/grass-user/2006-June/034795.html –  artwork21 Apr 15 '13 at 17:51

2 Answers 2

It is a pure geometry problem that can be solved in the Python console

The problem:

test

Find the midpoint of a segment x1,y1,x2,y2 is easy

x = (x1 + x2)/2
y = (y1 + y2)/2

so in the Python console

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

Result

final

share|improve this answer
    
Just a note that this approach finds the mid point of each line segment, not the line itself. –  Tim Sutton May 14 at 20:49

If you bring your line feature into spatialite, you can use the Line_Interpolate_Point() function to find the mid point.

SELECT AsText(Line_Interpolate_Point(your_line.geomemtry, 0.5))

The second parameter 0.5 indicates the fraction of the line length where the point will be located.

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.