Thursday 20 August 2015

How to get co ordinates of points on mouse click in PyQGIS


I want to get x/y co-ordinates of point on mouse click for a point and need to use those co-ordinates to evaluate other value as per others module already define .


How can I get x y coordinates on mouse click in QGIS and print those in PyQGIS.




Answer



You need QgsMapToolEmitPoint class to do that. Following code works well for that purpose:


from qgis.gui import QgsMapToolEmitPoint

def display_point( pointTool ):

print '({:.4f}, {:.4f})'.format(pointTool[0], pointTool[1])

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

However, if you prefer a class, following code can also be used:


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())
print '({:.4f}, {:.4f})'.format(point[0], point[1])


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

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...