Using Custom Python Expression Functions

Avvertimento

A new version of this tutorial is available at Using Custom Python Expression Functions (QGIS3)

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.

Descrizione dell’esercizio

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.

Altri aspetti che avremo modo di apprendere nel corso dell’esercizio

  • How to use the Map Tips tool to display custom text when hovering over a feature.

Ottenere i dati necessari

Utilizzeremo il dataset di Natural Earth Populated Places . Scarucate il simple (less columns) dataset

Per comodità, potete scaricare direttamente una copia del dataset dal seguente link:

ne_10m_populated_places_simple.zip

Procedimento

  1. Aprite QGIS e andate su Layer ‣ Aggiungi Layer ‣Aggiungi vettore...

../_images/1188.png
  1. Individuate lo shapefile appena scaricato ne_10m_populated_places_simple.zip e selezionatelo. Fate click su Apri.

../_images/2153.png
  1. Go to View ‣ Select ‣ Select By Expressions….

../_images/390.png
  1. Switch to the Function Editor tab. Here you can write any PyQGIS code that will be executed by the expression engine.

../_images/459.png
  1. We will define a custom function named 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.

Nota

Le zone UTM sono delle zone di proiezione longitudinale numerate da 1 a 60. Ogni zona UTM ha un’ampiezzza di 6 gradi. Qui utilizziamo una formula matematica semplice per individuare la zona appropriata per un dato valore di longitudine. Notate che questa formula non copre alcune zone UTM speciali.

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)
../_images/552.png
  1. Click Run Script. This will execute the python code and register the function 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.

../_images/650.png
  1. Switch to the Expression tab in the Select by expression dialog. Find and expand the Custom group in the Functions section. You will notice a new custom function $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'
../_images/750.png
  1. Back in the main QGIS window, you will see many points highlighted in yellow. These are the points falling in the UTM Zone we specified in the expression.

../_images/849.png
  1. You saw how we defined and used a custom function to select features by expression. We will now use the same function in another context. One of the hidden gems in QGIS is the 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.

../_images/950.png
  1. Switch to the Display tab and select HTML. Here you can enter any text that will be displayed when you hover over the features of the layer. Even better, you can use layer field values and expressions to define a much more useful message. Click on the Insert expression… button.

../_images/1057.png
  1. You will see the familiar expression editor again. We will use the 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)
../_images/1189.png
  1. You will see the expression entered as the value of the Display text. Click OK.

../_images/1259.png
  1. Before we proceed, let us de-select the features that were selected in the previous step. Go to View ‣ Select ‣ Deselect Features from All Layers.

../_images/1357.png
  1. Activate the Map Tips tool by going to View ‣ Map Tips.

../_images/1453.png
  1. Zoom into any area of the map and put your mouse cursor over any feature. You will see the name of the city and corresponding UTM zone displayed as the map tip.

../_images/1547.png

If you want to give feedback or share your experience with this tutorial, please comment below. (requires GitHub account)