5

Using QGIS expressions, it's easy to create a polygon with the extent (bounding box) covering all geometries of a layer using layer_property(@layer,'extent').

However, how do I get a polygon covering the whole layer extent, not only the extent of the geometry?

See the screenshot: the expression generates the blue polygon. However, I look for an expression generating a polygon symbolized here with the pink frame:

enter image description here

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
Babel
  • 71,072
  • 14
  • 78
  • 208

1 Answers1

7

You can define a custom function to get crs extent.

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom') def crs_extent(layer_name, feature, parent): layers = QgsProject.instance().mapLayersByName(layer_name)

if layers:
    bounds = layers[0].crs().bounds()
else:
    raise ValueError(f"Layer {layer_name} could not found")

return QgsGeometry.fromRect(bounds)


Result for crs_extent(@layer_name):

enter image description here

Result for crs_extent('OSM'): (No empty space at the top/bottom)

enter image description here

Note: Layer's CRS is WGS84 (EPSG:4326). If you use projected CRS for Layer, you may not get an expected result. For example, UTM's unit is meter, but crs().bounds() returns bounds in degree.

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389