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)
2
  • This can help you: gis.stackexchange.com/questions/253733/…
    – MrXsquared
    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.
    – Al110
    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

0

Your Answer

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

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