QGIS contains a built-in functionality to zoom and pan the map in custom applications. It also contains the basic hooks to build your own interactive tools. In this recipe, we'll create an interactive point tool that lets you mark locations on the map by clicking on a point.
We will use the application framework from the previous Adding standard map tools to the canvas recipe, so complete that recipe first. We will extend that application with a new tool. The complete version of this application is available in the code samples provided with this book.
We will set up the button, signal trigger, and actions as we do with all map tools. However, because we are building a new tool, we must also define a class to define exactly what the tool does. To do this, we need to perform the following actions:
QAction("Pan")
method:actionPoint = QAction("Point", self)
actionPoint.setCheckable(True)
self.connect(actionPoint, SIGNAL("triggered()"), self.point)
self.toolbar.addAction(actionPoint)
self.toolPoint = PointMapTool(self.canvas) self.toolPoint.setAction(actionPoint)
self.point()
def point(self): self.canvas.setMapTool(self.toolPoint)
canvasPressEvent
method, that receives the button-click event. We will inherit from a generic tool called the QgsMapToolEmitPoint
in order to create points:classPointMapTool(QgsMapToolEmitPoint): def __init__(self, canvas): self.canvas = canvas QgsMapToolEmitPoint.__init__(self, self.canvas) self.point = None defcanvasPressEvent(self, e): self.point = self.toMapCoordinates(e.pos()) printself.point.x(), self.point.y() m = QgsVertexMarker(self.canvas) m.setCenter(self.point) m.setColor(QColor(0,255,0)) m.setIconSize(5) m.setIconType(QgsVertexMarker.ICON_BOX) # or ICON_CROSS, ICON_X m.setPenWidth(3)