3

This question already has an answer here:

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?

marked as duplicate by Midavalo Mar 27 '17 at 0:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Does print on x,y return anything? – Nathan W Aug 9 '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 9 '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 9 '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 9 '14 at 11:31
  • Yeah they are the screen coordinates. Remove the other lines and just have the toMapCoordinates stuff. – Nathan W Aug 9 '14 at 12:09
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.

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