[GIS] Getting coordinates from mouse click in QGIS 3 (python plugin)

pyqgis-3pythonqgis-3qgis-plugins

I am trying to get coordinates from a mouse click in QGIS 3 and python 3 using the plugin builder.

I have tried using the response from this post, and i can manage to get the coordinates printed to the python console in QGIS but at the same time i get the message that "'TypeError: 'QgsMapToolEmitPoint' object is not iterable" or "'QgsMapToolEmitPoint' object does not support indexing"

I can't remember i ever seen a python program causing an error but still manage to compute and output the wanted result. The "not iterable" error traces back to the line with the for loop "for point in … "
the "does not support indexing" error is caused if i do e.g. x = pointTool[0]

Here is a version of the code:

from qgis.gui import QgsMapToolEmitPoint 

def display_point(pointTool):
    #print(pointTool)
    cood = []
    for point in pointTool:
        cood.append(point)
    print(cood)

# 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)

display_point(pointTool)

Best Answer

I have a little bit of a hard time getting the "canvasReleaseEvent" to return the x,y coordinates. At the moment i am writing my code into that function since it does output the x, y. (simply by stating "x=point.x()" etc).

I think i will try @xunilk's code and see if that would be easier.

https://webgeodatavore.github.io/pyqgis-samples/gui-group/QgsMapTool.html

# coding: utf-8
from PyQt4.QtCore import Qt
from qgis.gui import QgsMapTool
from qgis.utils import iface


class SendPointToolCoordinates(QgsMapTool):
    """ Enable to return coordinates from clic in a layer.
    """
    def __init__(self, canvas, layer):
        """ Constructor.
        """
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas
        self.layer = layer
        self.setCursor(Qt.CrossCursor)

    def canvasReleaseEvent(self, event):
        point = self.toLayerCoordinates(self.layer, event.pos())

        print(point.x(), point.y())

layer, canvas = iface.activeLayer(), iface.mapCanvas()

send_point_tool_coordinates = SendPointToolCoordinates(
    canvas,
    layer
)
canvas.setMapTool(send_point_tool_coordinates)
Related Question