3

I'm trying to build a plugin that firstly captures the map coordinates.

I have tried to adapt the map tool explained in this post: How to programatically check for a mouse click in QGIS

The code I used for the main function is below:

def canvasReleaseEvent(self, event):
    #Get the click
    x = event.pos().x()
    y = event.pos().y()

    canvas = self.canvas
    canvas.mapRenderer().setProjectionsEnabled(True)
    canvas.mapRenderer().setDestinationCrs(QgsCoordinateReferenceSystem(27700))
    espg = canvas.mapRenderer().destinationCrs().authid()

    point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)

Unfortunately the when I print point it always returns as (0,0). I have tried various ways to set the crs of the points but none work. What needs to be done to make it work?

Matt T
  • 688
  • 3
  • 9
  • 25
  • Does print on x,y return anything? – Nathan W Aug 09 '14 at 11:11
  • 2
    Also don't do setProjectionsEnabled or setDestinationCrs. That is changing the canvas itself which might not be what you want. Use QgsCoordinateTransform if you need to transform from one to the other, or just toMapCoordinates is enough to go from click to canvas coordinates – Nathan W Aug 09 '14 at 11:14
  • Thanks @Nathan W - I was just being explicit with the crs to make sure it wasn't that. – Matt T Aug 09 '14 at 11:25
  • print x, print y does return values. These aren't recognisable to me though. All are three digit couplets like 356,172? – Matt T Aug 09 '14 at 11:31
  • Yeah they are the screen coordinates. Remove the other lines and just have the toMapCoordinates stuff. – Nathan W Aug 09 '14 at 12:09

1 Answers1

0

This should do it:

class PointTool(QgsMapToolEmitPoint):
def __init__(self, canvas):
    QgsMapToolEmitPoint.__init__(self, canvas)

def canvasReleaseEvent(self, mouseEvent):
    qgsPoint = self.toMapCoordinates(mouseEvent.pos())
    print('x:', qgsPoint.x(), ', y:', qgsPoint.y())

As your question is possibly a duplicate to this post.

Henhuy
  • 886
  • 5
  • 19