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
35.7k5 gold badges77 silver badges151 bronze badges
asked Oct 4, 2021 at 7:26
2
  • This can help you: gis.stackexchange.com/questions/253733/… Commented Oct 4, 2021 at 7: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. Commented Oct 4, 2021 at 11:11

1 Answer 1

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

answered Oct 4, 2021 at 15:56
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.