Adding a logo to the map

An important part of customizing a map is to add your logo or other graphics to the composition. In this recipe, we'll add a simple logo to the map.

Getting ready

You will need to download the following zipped shapefile and extract it to your qgis_data directory, to a subdirectory named ms:

https://geospatialpython.googlecode.com/svn/Mississippi.zip

You will also need a logo image, which you can download from https://geospatialpython.googlecode.com/svn/trunk/logo.png.

Place the image in your qgis_data/rasters directory.

If you haven't already done so in the previous recipe, download 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.

How to do it...

In this recipe, we will create the map composition, add the logo image, and save the map as an image. To do this, we need to perform the following steps:

  1. First, we need to import the Qt GUI, core QGIS, QGIS GUI, and MapComposer libraries:
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from qgis.core import *
    from qgis.gui import *
    import MapComposer
    
  2. Next, we will build a basic map composition using the shapefile:
    lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
    reg = QgsMapLayerRegistry.instance()
    reg.addMapLayer(lyr)
    mr = iface.mapCanvas().mapRenderer()
    qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
    
  3. Now, we initialize the picture object:
    qc.logo = QgsComposerPicture(qc.c)
    
  4. Then, we set the path of the picture to our image file:
    qc.logo.setPictureFile("/qgis_data/rasters/logo.png")
    
  5. We must set the size of the box or scene rectangle such that it is large enough to contain the logo. Otherwise, the picture will appear cropped:
    qc.logo.setSceneRect(QRectF(0,0,50,70))
    
  6. Next, we calculate the position of the logo relative to the map image. We'll place the logo near the top-left corner of the map:
    lx = qc.x + 50
    ly = qc.y – 120
    
  7. Now, we set the logo's position and add it to the map composition:
          mcw = qc.composerMap.rect().width()
          mch = qc.composerMap.rect().height()
          lx =  qc.x
    ly =  qc.y - 20
    
  8. Finally, we save the composition as an image:
    qc.output("/qgis_data/map.jpg", "jpg")
    

How it works...

This recipe is very straight forward, as the QgsComposerPicture is an extremely simple object. You can use JPG, PNG, or SVG images. This technique can be used to add custom north arrows or other cartographic elements as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset