6

I want to display the extents of print composer maps in the main canvas as polygons ("map footprints"). Currently I am using the geometry generator with the expression make_rectangle_3points and then copying the extent coordinates from the print composer maps to the expression, e.g.:

make_rectangle_3points(
    make_point(463465.676,4535861.289),
    make_point(463465.676,4527494.964),
    make_point(472029.374,4527494.964),
    0)

This process is somewhat time consuming and prone to errors. Does anybody have a better idea how to achieve this?

3 Answers 3

16

There is a native feature in QGIS to display print extents in the map canvas.

But if you want proper GIS polygons in a layer, you should indeed use some PyQGIS with the script provided in the other answer.

enter image description here

0
8

PyQGIS is a solution.

Below a script that creates a new memory layer with you map item extent as a polygon and adds it to the canvas.

You have just to configure the constants with your layout name and map item ID, then execute it in the QGIS Python console.

### constants ###
LAYOUT_NAME = "my_layout"
MAP_ITEM_ID = "Map 1"

# create a memory layer with map item extent
project = QgsProject.instance()

lyt_manager = project.layoutManager()
try:
    lyt = [i for i in lyt_manager.layouts() if i.name() == LAYOUT_NAME][0]
except IndexError:
    raise IndexError(f"No layout named '{LAYOUT_NAME}' was found")

map_item = lyt.itemById(MAP_ITEM_ID)

project_crs = project.crs().authid()
vl = QgsVectorLayer(f"Polygon?crs={project_crs}", "my_layout_extent", "memory")
pr = vl.dataProvider()

with edit(vl):
    feat = QgsFeature()
    feat.setGeometry(QgsGeometry.fromRect(map_item.extent()))
    pr.addFeatures([feat])

QgsProject.instance().addMapLayer(vl)
2
  • Can't try this right now, but wouldn't it be better to create the memory layer in the layout's CRS, rather than the project's CRS, letting QGIS transform on the fly when displaying it? Would better handle the situation where one layout (e.g. for a tiled webmap) is in a different CRS (e.g. EPSG:3857) than the project default (e.g. UTM).
    – Houska
    Sep 1, 2022 at 10:24
  • 1
    I think the layout map item extent CRS is the project CRS, so, to not give a more complicated code with CRS transformation and hypothetical layer (this code work even if there is no layer), I posted this one. Sep 1, 2022 at 12:04
5

I just found that QGIS also has a processing algorithm called "Print layout map extent to layer" which also works very well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.