Atlas item in Qgis
- In Qgis, add a vector layer and create the desired features
- Open the Print composer. In the toolbar go to Atlas -> Atlas Settings
- In the new window, check the box at Generate an atlas and choose your vector layer as coverage layer.
- In the toolbar go to Atlas -> Preview Atlas. The map will now update.
You can cycle through the features using the arrows.
The downside of this method is that we first need to draw the features in the location. It also doesn't provide the flexibilty of drag and zooming to the exact view you wish to print. The code below will do just that.
How to run python code in Qgis
To run Python, first enable the console by going to Plugins -> Python Console or pressing Ctrl + Alt + P. The console will open as a docked widget. The code below can be pasted here.
Alternative, you can store the code in a python (.py) file. In the docket widget, click the Show Editor icon. In the new window you can create a new editor and paste the code there. Save the file as a .py on your computer and run the code by pressing the Run Script button.
PyQgis code to update all items
The code below use the Pygis Python library to update all map items of the first open layout it can find. To use it, drag your Qgis view to the area you want the print. Open your Print Composer layout and run the code in the Qgis' Python console (see above). The code is explained in detail below.
# Sets the zoom extent of all maps in an open layout layout = iface.openLayoutDesigners().layout() # Get the first layout canvas = iface.mapCanvas() # Get the map canvas for item in layout.items(): if(item.type() == 65639): # If the item is a Map Item item.zoomToExtent(canvas.extent()) # set the extent
The first line select the first (
QgsLayoutDesigner and stores a reference the the current layout. The next line stores a reference to the canvas item of the main Qgis window.
By iterating over the items and comparing the type with this of a
QgsLayoutItemMap (65639, notice an ItemMap is not the same as a MapItem) we can select the maps and zoom to the Qgis canvas extent using
It is import to use the
zoomToExtent() instead of the
setExtent() method. The latter will also change the width and height of the map, so that it matches exactly the specified extent.