1

I can not figure out how to input the coordinates through a mouse click instead of the code below. I am trying to create a temporary layer of a point from a mouse click. Everything seems to work except for that I can not figure the coordinates out.

from qgis.PyQt.QtCore import QVariant

vl = QgsVectorLayer("Point", "POI", "memory")
pr = vl.dataProvider() pr.addAttributes([QgsField("ID", QVariant.String)]) vl.updateFields() f = QgsFeature() f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(10,10))) f.setAttributes(["1"])

pr.addFeature(f) vl.updateExtents() QgsProject.instance().addMapLayer(vl)

Taras
  • 32,823
  • 4
  • 66
  • 137
Al110
  • 35
  • 3
  • This can help you: https://gis.stackexchange.com/questions/253733/getting-coordinates-of-point-on-mouse-click-using-pyqgis/253738#253738 – MrXsquared Oct 04 '21 at 07:39
  • Thank you! Even using this to help though, I can not find out how to add the selected point from this tool to a field, or even just regular lat and long coordinates into this code. – Al110 Oct 04 '21 at 11:11

1 Answers1

3

Combining lines in this link and your code, it looks as follows:

from qgis.gui import QgsMapToolEmitPoint
from qgis.PyQt.QtCore import QVariant

def display_point( pointTool ):

vl = QgsVectorLayer("Point", "POI", "memory")    
pr = vl.dataProvider()
pr.addAttributes([QgsField("ID", QVariant.String)])
vl.updateFields() 
f = QgsFeature()
f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(pointTool[0],pointTool[1])))
f.setAttributes(["1"])

pr.addFeature(f)
vl.updateExtents() 
QgsProject.instance().addMapLayer(vl)

a reference to our map canvas

canvas = iface.mapCanvas()

this QGIS tool emits as QgsPoint after each click on the map canvas

pointTool = QgsMapToolEmitPoint(canvas)

pointTool.canvasClicked.connect( display_point )

canvas.setMapTool( pointTool )

After running it in Python Console of QGIS 3, it can be observed in following image, after 10 mouse clicks, there were produced 10 point layers as expected.

enter image description here

xunilk
  • 29,891
  • 4
  • 41
  • 80