Expressions in QGIS have a lot of power and are used in many core features - selection, calculating field values, styling, labelling etc. QGIS also has support for user-defined expressions. With a little bit of python programming, you can define your own functions that can be used within the expression engine.
We will define a custom function that finds the UTM Zone of a map feature and use this function to write an expression that displays the UTM zone as a map tip when hovered over the point.
Map Tips
tool to display custom text when hovering over a
feature.We will use Natural Earth’s Populated Places dataset. Download the simple (less columns) dataset
For convenience, you may directly download a copy of the dataset from the links below:
ne_10m_populated_places_simple.zip
file and
click Open.GetUtmZone
that will calculate
the UTM zone number for each feature. Since custom functions in QGIS work at
the feature level. We will use the centroid of the feature’s geometry and
compute the UTM Zone from the latitude and longitude of the centroid
geometry. We will also add a ‘N’ or ‘S’ designation to the zone to indicate
whether the zone is in the northern or southern hemisphere. Type the
following code in the editor, enter the name of the file as utm_zones.py
and click Save file.Note
UTM Zones are longitudinal projection zones numbered from 1 to 60. Each UTM zone is 6 degree wide. Here we use a simple mathematical formula to find the appropriate zone for a given longitude value. Note that this formula doesn’t cover some special UTM zones.
import math
from qgis.core import *
from qgis.gui import *
@qgsfunction(args=0, group='Custom', usesgeometry=True)
def GetUtmZone(value1, feature, parent):
centroid = feature.geometry()
longitude = centroid.asPoint().x()
latitude = centroid.asPoint().y()
zone_number = math.floor(((longitude + 180) / 6) % 60) + 1
if latitude >= 0:
zone_letter = 'N'
else:
zone_letter = 'S'
return '%d%s' % (int(zone_number), zone_letter)
GetUtmZone
with the expression engine. Note that this is
needed to be done only once. Once the function is registered, it will always
be available to the expression engine.$GetUtmZone
in the list. We can now use this function in the expressions
just like any other function. Type the following expression in the editor.
This expression will select all points that fall in the UTM Zone 40N
.
Click Select.$GetUtmZone = '40N'
Map Tip
tool. This tool shows user-defined
text when you hover over a feature. Right-click the
ne_10m_populated_places_simple
layer and select Properties.concat
function to join the value of the field name
and the result
of our custom function $GetUtmZone. Enter the following expression and
click OK.concat("name", ' | UTM Zone: ', $GetUtmZone)
Map Tips
tool by going to .This work is licensed under a Creative Commons Attribution 4.0 International License