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 endpoint 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()
break
if id != -1:
print feats[id].attribute('name')
else:
print "no feature selected"
canvas = iface.mapCanvas()
pointTool = QgsMapToolEmitPoint(canvas)
pointTool.canvasClicked.connect(display_point)
canvas.setMapTool(pointTool)