In this recipe, you'll learn how to add standard map navigation tools to a standalone map canvas. Creating the simplest possible interactive application provides a framework to begin building specialized geospatial applications using QGIS as a library.
Download the following zipped shapefile and extract it to your qgis_data
directory into a folder named ms
from https://geospatialpython.googlecode.com/files/Mississippi.zip.
We will walk through the steps required to create a map canvas, add a layer to it, and then add some tools to zoom and pan the map, as follows:
from qgis.gui import * from qgis.core import * from PyQt4.QtGui import * from PyQt4.QtCore import SIGNAL, Qt import sys, os
# OSX: QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True) # Windows: # app.setPrefixPath("C:/Program Files/QGIS Valmiera/apps/qgis", True)
class MyWnd(QMainWindow): def __init__(self):
QMainWindow.__init__(self) QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True) QgsApplication.initQgis() self.canvas = QgsMapCanvas() self.canvas.setCanvasColor(Qt.white)
self.lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/mississippi.shp", "Mississippi", "ogr") QgsMapLayerRegistry.instance().addMapLayer(self.lyr) self.canvas.setExtent(self.lyr.extent()) self.canvas.setLayerSet([QgsMapCanvasLayer(self.lyr)]) self.setCentralWidget(self.canvas)
actionZoomIn = QAction("Zoom in", self) actionZoomOut = QAction("Zoom out", self) actionPan = QAction("Pan", self) actionZoomIn.setCheckable(True) actionZoomOut.setCheckable(True) actionPan.setCheckable(True)
actionZoomIn.triggered.connect(self.zoomIn) actionZoomOut.triggered.connect(self.zoomOut) actionPan.triggered.connect(self.pan)
self.toolbar = self.addToolBar("Canvas actions") (actionZoomIn) self.toolbar.addAction(actionZoomOut) self.toolbar.addAction(actionPan)
self.toolPan = QgsMapToolPan(self.canvas) self.toolPan.setAction(actionPan) self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in self.toolZoomIn.setAction(actionZoomIn) self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out self.toolZoomOut.setAction(actionZoomOut)
self.pan()
defzoomIn(self): self.canvas.setMapTool(self.toolZoomIn) defzoomOut(self): self.canvas.setMapTool(self.toolZoomOut) def pan(self): self.canvas.setMapTool(self.toolPan)
class MainApp(QApplication): def __init__(self): QApplication.__init__(self,[],True) wdg = MyWnd() wdg.show() self.exec_()
if __name__ == "__main__": import sys app = MainApp()
An application is a continuously running program loop that ends only when we quit the application. QGIS is based on the Qt windowing library, so our application class inherits from the main window class that provides the canvas and the ability to create toolbars and dialogs.This is a lot of setup, even for an extremely simple application, but once the framework for an application is complete, it becomes much easier to extend it.