QGIS 3.10 introduces two new features [1, 2] that allows you to dynamically change the size of the grid when scaling.
However, when using this new feature, the interval between the grid lines can take odd values, in addition, the grid cells are rectangular, which is ugly in my opinion.
To solve this problem and get pretty square grid with predefined 1, 2, 4, 8, 15, 30
intervals (see animation here) you can use the following instruction:
- Open your
map
item properties and expand Grids
tab.
- Create new grid and push
Modify Grid...
button.
- Choose interval value
Map Unit
.
- Push
Data defined Override
button and click edit
.
- Copy and paste custom function code to the
Function Editor
tab and push Save and Load Functions
button.
- Copy and paste expression code for X and Y intervals separately (see code below).
Expression code for x intervals:
get_interval(
(
x( point_n( transform(@map_extent, @project_crs ,'EPSG:4326'), 2)) -
x( point_n( transform(@map_extent, @project_crs ,'EPSG:4326'), 1))
) / 4
)
Expression code for y intervals:
get_interval(
(
x( point_n( transform(@map_extent, @project_crs ,'EPSG:4326'), 2)) -
x( point_n( transform(@map_extent, @project_crs ,'EPSG:4326'), 1))
) / 8
)
Custom function code:
import bisect
@qgsfunction(args='auto', group='Custom')
def get_interval(extent_length, feature, parent):
"""Input is current extent length
Output is optimal round value
"""
intvals = [1/3600, 2/3600, 4/3600, 8/3600, 15/3600, 30/3600,
1/60, 2/60, 4/60, 8/60, 15/60, 30/60,
1, 2, 4, 8, 15, 30]
i = bisect.bisect_right(intvals, extent_length)
return intvals[i]