I have an empty layer in QGIS in that i just want to draw a polyline by selecting points on layer using Python.

For Example if i select a start point and end point on a layer , i want to draw a line connecting to those points using python code. i have gone through all related references but i didn't get it.

what i have tried is :

from qgis.gui import QgsMapToolEmitPoint
def display_point(point, mouse_button):
  coords = "Map Coordinates: {:.4f}, {:.4f}".format(point.x(), point.y())
  print coords
  layer = iface.activeLayer()
  feats = [ feat for feat in layer.getFeatures() ]
  geo_pt = QgsGeometry.fromPoint(QgsPoint(point.x(), point.y()))
  id = -1
  for feat in feats:
    if geo_pt.within(feat.geometry()):
      id = feat.id()
  if id != -1:
    print feats[id].attribute('name')
    print "no feature selected"
canvas = iface.mapCanvas()
pointTool = QgsMapToolEmitPoint(canvas)

You could try to identify the selected features of the source layer with


and then create a line geometry from the list of points:

line = QgsGeometry.fromPolyline(list_of_points)
| improve this answer | |
  • I got this error : AttributeError: 'QgsVectorLayer' object has no attribute 'getSelectedFeatures' – Virat ABD Aug 23 '18 at 6:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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