Created
March 30, 2020 10:01
-
-
Save NyakudyaA/c2cf728e2906288e0448f82cb3c5a077 to your computer and use it in GitHub Desktop.
QGIS function to create dynamic map grids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Define new functions using @qgsfunction. feature and parent must always be the | |
last args. Use args=-1 to pass a list of values as arguments | |
""" | |
from qgis.core import Qgis, QgsProject,QgsCoordinateTransform,QgsCoordinateReferenceSystem | |
from qgis.gui import * | |
from qgis.utils import qgsfunction, iface | |
def map_bounds(composer_title, map_id): | |
projectInstance = QgsProject.instance() | |
projectLayoutManager = projectInstance.layoutManager() | |
layout = projectLayoutManager.layoutByName(composer_title) | |
map=layout.itemById(map_id) | |
transform = QgsCoordinateTransform(QgsCoordinateReferenceSystem("EPSG:3857"),QgsCoordinateReferenceSystem("EPSG:4326"),projectInstance ) | |
bbox= map.extent() | |
extent=transform.transformBoundingBox(bbox) | |
return extent | |
@qgsfunction(args='auto', group='Custom') | |
def map_x_min(composer_title, map_id, feature, parent): | |
""" | |
Calculates the map_x_min of the map layout. | |
<h2>Example usage:</h2> | |
<ul> | |
<li>map_x_min(composer_title, map_id) </li> | |
<li>map_x_min('sample_map', 'main') </li> | |
</ul> | |
""" | |
map_extent = map_bounds(composer_title, map_id) | |
x_min = map_extent.xMinimum() | |
return x_min | |
@qgsfunction(args='auto', group='Custom') | |
def map_x_max(composer_title, map_id, feature, parent): | |
""" | |
Calculates the map_x_min of the map layout. | |
<h2>Example usage:</h2> | |
<ul> | |
<li>map_x_max(composer_title, map_id) </li> | |
<li>map_x_max('sample_map', 'main') </li> | |
</ul> | |
""" | |
map_extent = map_bounds(composer_title, map_id) | |
x_max = map_extent.xMaximum() | |
return x_max | |
@qgsfunction(args='auto', group='Custom') | |
def map_y_min(composer_title, map_id, feature, parent): | |
""" | |
Calculates the map_x_min of the map layout. | |
<h2>Example usage:</h2> | |
<ul> | |
<li>map_y_min(composer_title, map_id) </li> | |
<li>map_y_min('sample_map', 'main') </li> | |
</ul> | |
""" | |
map_extent = map_bounds(composer_title, map_id) | |
y_min = map_extent.yMinimum() | |
return y_min | |
@qgsfunction(args='auto', group='Custom') | |
def map_y_max(composer_title, map_id, feature, parent): | |
""" | |
Calculates the map_x_min of the map layout. | |
<h2>Example usage:</h2> | |
<ul> | |
<li>map_y_max(composer_title, map_id) </li> | |
<li>map_y_max('sample_map', 'main') </li> | |
</ul> | |
""" | |
map_extent = map_bounds(composer_title, map_id) | |
y_max = map_extent.yMaximum() | |
return y_max |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment