Geographic Information Systems Asked on May 2, 2021
I have a script that creates a print layout and contains all of my vector/raster layers. I have changed my extent to ‘mem_layer’, which is my buffer layer I am using for this project. However, when I view the print layout, the extent is so far zoomed in on the buffer layer, that it is impossible to view the location around it. If I go into the layout manually and change the scale to 8500000, then my map works perfectly. Using PyQGIS, is there any way I can incorporate to add/change the scale of the extent to 8500000, so that I can view my map more clearer. My script is as follows:
project = QgsProject.instance() #gets a reference to the project instance
manager = project.layoutManager() #gets a reference to the layout manager
layout = QgsPrintLayout(project) #makes a new print layout object, takes a QgsProject as argument
layoutName = "PrintLayout"
layouts_list = manager.printLayouts()
for layout in layouts_list:
if layout.name() == layoutName:
manager.removeLayout(layout)
layout = QgsPrintLayout(project)
layout.initializeDefaults() #create default map canvas
layout.setName(layoutName)
manager.addLayout(layout)
#This adds a map item to the Print Layout
map = QgsLayoutItemMap(layout)
map.setRect(20, 20, 20, 20)
#Set Extent
#rectangle = QgsRectangle(1355502, -46398, 1734534, 137094) #an example of how to set map extent with coordinates
#map.setExtent(rectangle)
canvas = iface.mapCanvas()
map.setExtent(mem_layer.extent())
layout.addLayoutItem(map)
#Move & Resize
map.attemptMove(QgsLayoutPoint(5, 27, QgsUnitTypes.LayoutMillimeters))
map.attemptResize(QgsLayoutSize(239, 178, QgsUnitTypes.LayoutMillimeters))
What the map on the layout currently shows:
What I would like the map to show when I change the scale is 8500000 using PyQGIS:
With the documentation of QgsLayoutItemMap, you'll find the setScale method.
setScale(self, scale: float, forceUpdate: bool = True)
Sets new map `scale` and changes only the map extent. The `scale` value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map.
So, in your code, try:
# [...]
map.setExtent(mem_layer.extent())
map.setScale(8500000)
# [...]
Correct answer by J. Monticolo on May 2, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP