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?
1 Answer 1
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.
QgsCoordinateTransform
if you need to transform from one to the other, or justtoMapCoordinates
is enough to go from click to canvas coordinates