[GIS] Setting the extent for a QGIS map using python

pyqgispythonqgis

I am writing a stand-alone application in Python/QGIS that simply creates maps.

I want to load vector/raster layers, set symbology, set extent

At the moment, that is all!

Currently I am just using the simple rendering technique outlined here: http://www.qgis.org/pyqgis-cookbook/composer.html#simple-rendering

I have failed, however, at adapting this code to define a specific extent. I provide the code below.

The only examples that I can find that show how to change extent involve creating a MapCanvas. …But I am not certain that this is something I want to do considering I am just making very simple maps…and it seems to introduce a whole new set of complications. Surely there is an easy way to define extent via the 'simple rendering' technique?

Becky

from qgis.core import *
from qgis.utils import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtCore import QFileInfo, QSettings

QgsApplication.setPrefixPath('/Applications/QGIS-1.9.app/Contents/MacOS', True)
QgsApplication.initQgis()

province = QgsVectorLayer('/filepath/Province_studyUTM36S.shp' , 'layer', 'ogr')
town = QgsVectorLayer('/filepath/TownPolygons_UTM36S.shp' , 'layer', 'ogr')
road = QgsVectorLayer('/filepath/Roads_UTM36S.shp' , 'layer', 'ogr')

QgsMapLayerRegistry.instance().addMapLayer(province)
QgsMapLayerRegistry.instance().addMapLayer(road)
QgsMapLayerRegistry.instance().addMapLayer(town)

rasterFile = '/filepath/Landsat.tif'
fileInfo = QFileInfo(rasterFile)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(rasterFile, baseName)


QgsMapLayerRegistry.instance().addMapLayer(rlayer)

img = QImage(QSize(800,600), QImage.Format_ARGB32_Premultiplied)  

color = QColor(255,255,255) 
img.fill(color.rgb())  

p = QPainter() 
p.begin(img) 
p.setRenderHint(QPainter.Antialiasing)  
render = QgsMapRenderer()  
ID = [  rlayer.getLayerID(), town.getLayerID(), road.getLayerID(), province.getLayerID()] 
render.setLayerSet(ID)  


rect = QgsRectangle(render.fullExtent()) 
rect.scale(1.1) 
render.setExtent(rect)  

render.setOutputSize(img.size(), img.logicalDpiX())  

render.render(p)  
p.end()  

img.save("/filepath/first_render.png","png")

Best Answer

Perhaps it would suffice for you to simply save the map canvas as an image after zooming to the extent of interest. Making use of mapCanvas() doesn't add too many lines of code and would export a simple PNG.

From the python console, this code would produce a simple screen capture of the area oriented around a selected feature, all active layers, and any activated labels:

qgis.utils.iface.actionZoomToSelected().trigger()
qgis.utils.iface.mapCanvas().zoomScale(1000)

qgis.utils.iface.mapCanvas().saveAsImage('test.png', None, 'PNG') 
Related Question