An annotated reference grid is useful for map products used to locate features. This recipe teaches you how to add both reference lines on a map and annotations for the lines around the edges of the map.
You will need a shapefile for this map from https://geospatialpython.googlecode.com/svn/Mississippi.zip, and you need to extract it to your qgis_data
directory, to a subdirectory named ms
.
As with the previous recipes in this chapter, we will use the MapComposer
library from https://geospatialpython.googlecode.com/svn/MapComposer.py to simplify the creation of the map composition.
Place the file in the .qgis2/python
directory within your home directory.
In this recipe, the general steps are to create the map composition, establish the overall grid parameters, define the grid line placement, and then style the grid and annotations. To do this, we need to perform the following steps:
from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * from qgis.gui import * import MapComposer
lyr = QgsVectorLayer("/qgis_data/ms/mmississippi.shp", "Mississippi", "ogr") reg = QgsMapLayerRegistry.instance() reg.addMapLayer(lyr) mr = iface.mapCanvas().mapRenderer() qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
setGridAnnoPos = qc.composerMap.setGridAnnotationPosition setGridAnnoDir = qc.composerMap.setGridAnnotationDirection qcm = QgsComposerMap
qc.composerMap.setGridEnabled(True) qc.composerMap.setGridIntervalX(.75) qc.composerMap.setGridIntervalY(.75) qc.composerMap.setGridStyle(qcm.Solid)
qc.composerMap.setShowGridAnnotation(True) qc.composerMap.setGridAnnotationPrecision(0)
setGridAnnoPos(qcm.OutsideMapFrame, qcm.Top) setGridAnnoDir(qcm.Horizontal, qcm.Top) setGridAnnoPos(qcm.OutsideMapFrame, qcm.Bottom) setGridAnnoDir(qcm.Horizontal, qcm.Bottom) setGridAnnoPos(qcm.OutsideMapFrame, qcm.Left) setGridAnnoDir(qcm.Vertical, qcm.Left) setGridAnnoPos(qcm.OutsideMapFrame, qcm.Right) setGridAnnoDir(qcm.Vertical, qcm.Right)
qc.composerMap.setAnnotationFrameDistance(1) qc.composerMap.setGridPenWidth(.2) qc.composerMap.setGridPenColor(QColor(0, 0, 0)) qc.composerMap.setAnnotationFontColor(QColor(0, 0, 0)) qc.c.addComposerMap(qc.composerMap)
qc.output("/qgis_data/map.jpg", "jpg")
Verify that your output image looks similar to the following:
This recipe has a lot of steps because the grids are customizable. The order of operations is important as well. Notice that we do not add the map to the composition until the very end. Often, you will make what seem to be minor changes and the grid may not render. Hence, modify this recipe carefully.