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 have a situation like this:

enter image description here

What I need to do is to connect each point to every line that is at most, let's say 200 m, away from the point. In other words, I need to draw a perpendicular line from each point to every line that is in the buffer.

Is there a way to do this in QGIS and PyQGIS?


share|improve this question

1 Answer 1

up vote 14 down vote accepted

It is a problem of analytical geometry and the solution was given by Paul Bourke in 1998 (Minimum Distance betweena Point and a Line). The shortest distance from a point to a line or line segment is the perpendicular from this point to the line segment. Several versions of his algorithm have been proposed in various languages ​​including Python as in Measuring distance from a point to a line segment in Python. but there are many others (like Nearest neighbor between a point layer and a line layer with Shapely)

# basic example with PyQGIS
# the end points of the line
line_start = QgsPoint(50,50)
line_end = QgsPoint(100,150)
# the line
line = QgsGeometry.fromPolyline([line_start,line_end])
# the point
point = QgsPoint(30,120)

pt line

def intersect_point_to_line(point, line_start, line_end):
     ''' Calc minimum distance from a point and a line segment and intersection'''
      # sqrDist of the line (PyQGIS function = magnitude (length) of a line **2)
      magnitude2 = line_start.sqrDist(line_end) 
      # minimum distance
      u = ((point.x() - line_start.x()) * (line_end.x() - line_start.x()) + (point.y() - line_start.y()) * (line_end.y() - line_start.y()))/(magnitude2)
      # intersection point on the line
      ix = line_start.x() + u * (line_end.x() - line_start.x())
      iy = line_start.y() + u * (line_end.y() - line_start.y())
      return QgsPoint(ix,iy)

line = QgsGeometry.fromPolyline([point,intersect_point_to_line(point, line_start, line_end)])

and the result is


Adapting the solution to your problem is easy,just loop through all line segments, extracting the segments end points and apply the function.

share|improve this answer
This is the best answer anyone has ever given to any question, ever! Thanks! –  PeterBorook Apr 26 '13 at 9:18

Your Answer


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.