1

I'm doing some stuff with digitizing and one thing that would nice to have is to get coordinates by mouse click.

My problem is that I don't know how can I create utility similar to this from map tool, where I can easly create method:

def canvasReleaseEvent(self, e):
    if e.button() == Qt.LeftButton:
        x = e.pos().x()
        y = e.pos().y()

        point = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(x, y)
        print(point)

For example, when user wants to digitizing, he has to show a point on canvas, where to start. To do this, he clicks on a button to call a function for getting coordinates from canvas.

The main problem I struggle with is that I don't know how I can craete method for catching coordinates, that only works when I call it (not like in maptool, when it works all the time).

Is there any way to do that?

1
  • Go for e.mapPoint() if using a recent (>=2.12) version of QGIS. There are also snapping tools directly built into the click event if you need to get a nearby-object (e.snapPoint()). Dec 1, 2016 at 10:30

2 Answers 2

3

The following code returns a list of XY Coordinates of the region in a map canvas where clicked.

from qgis.gui import QgsMapToolEmitPoint

class PrintClickedPoint(QgsMapToolEmitPoint):
    def __init__(self, canvas):
        self.canvas = canvas
        QgsMapToolEmitPoint.__init__(self, self.canvas)

    def canvasPressEvent( self, e ):
        point = self.toMapCoordinates(self.canvas.mouseLastXY())
        point = list(point)
        print point

canvas_clicked = PrintClickedPoint( iface.mapCanvas() )
iface.mapCanvas().setMapTool( canvas_clicked )
2

With any recent (>= 2.12) version of QGIS, the canvasXyzEvents receive a QgsMapMouseEvent which has additional methods that make working with the canvas straightforward.

def canvasReleaseEvent(self, e):
    if e.button() == Qt.LeftButton:
        # will always return the real position in the map CRS
        point = e.originalMapPoint()
        # The following will return a snapped point
        snappedPoint = e.snapPoint(QgsMapMouseEvent.SnapProjectConfig)

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