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)
-
This can help you: gis.stackexchange.com/questions/253733/…MrXsquared– MrXsquared2021年10月04日 07:39:30 +00:00Commented 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.Al110– Al1102021年10月04日 11:11:24 +00:00Commented Oct 4, 2021 at 11:11
1 Answer 1
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.
Explore related questions
See similar questions with these tags.