Functions in QGIS expressions

The definition of a function in a programming language is quite different from the definition of a mathematical function. In the computer field, a function refers to a program or code that can be directly referenced by another program or code, also called a subroutine, procedure, or method.

Functions play an important role in the construction of QGIS expressions. Expressions are actually the results of functions acting on constants and variables. It can be said that functions are the soul of expressions.

Built-in functions and custom functions

The functions in QGIS expressions are divided into two categories : built-in functions and custom functions .

Built-in functions are built-in functions of the QGIS system. Users can call the built-in functions during expression construction, but cannot modify the code in them.

Custom functions are code snippets written by users in Python language, which can be designed and modified according to individual needs, providing users with more powerful and flexible customization capabilities.

  • System built-in functions

QGIS built-in functions are divided into about 20 groups, including maps, map layers, records and attributes, time and date, math, arrays, conditions, etc. The number of functions included in each group is as follows:
Insert picture description here

  • Custom function

Switch to the [Function Editor] tab in the expression builder, you can see that the custom function editing area is composed of the function list on the left, the function code editor on the upper right, and the help area on the lower right.

By default, the function list has only one default function, which is a custom function template provided by the system. The function code editor on the right gives sample codes, and provides references for importing QGIS modules, custom function storage groups, and function body codes.
Insert picture description here

Click the [+] button in the lower left corner and enter the stored file name in the pop-up dialog box to add a custom function.

Insert picture description here

Under normal circumstances, a custom function first needs to use the import statement to import the referenced Python library, and then design and write the function implementation code, for example, enter the following code in the function code editor:

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

@qgsfunction(args=0, group='Custom', usesgeometry=True)
def GetUtmZone(value1, feature, parent):
    """以字符串形式返回几何图形所属的UTM区"""
    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)

The main function of this function is to calculate the UTM projection index zone where the element is located, and return the projection index zone string ending in'N' or'S'.
Insert picture description here

Click the [Save and Load Function] button in the lower right corner to save the function and load it into the corresponding group of the expression builder. At this time, call up the expression builder dialog box, you can see the above-mentioned custom function appears in the custom group, double-click the function to complete the function call.
Insert picture description here

Custom functions can be designed and coded according to requirements, which provides more possibilities for the use of functions. Since the Python programming language is involved, its usage is more complicated. The official QGIS document has a lot of space to detail this aspect. Introduction, interested friends can go to QGIS official website to check related documents.

Find function

In the expression builder, functions are listed in a tree structure in groups. If you are familiar with the grouping of functions and have a general understanding of which group the function you need belongs to, you can directly expand the grouping to find the function. If you know the name of the function, you can enter the name of the function in the search box above the selection area to find it quickly.
Insert picture description here

Use function

Double-click the function to add it to the code input area. The expression code editor supports parameter prompting and auto-completion functions: input the first few letters of the function, the editor will prompt the matching function name, and use the tab button to realize automatic completion.

Functions in QGIS support named parameters, that is, when using the function, the incoming parameters can be named parameters. Named parameters can ignore the order of the parameters, which is convenient for the use of functions, especially when there are many parameters, the method of using parameter names and parameter values ​​at the same time can improve the readability of the code.

For example, the clamp function can limit the input value to a specified range. Three parameters are required: min, the minimum value of the range; max, the maximum value of the range; value, the input value. By default, the parameter call sequence of the clamp function is: clamp(min,value,max). For example, write the code in the expression editing area: clamp(1,5,10) to limit the input value to [1 ,10] range, the current input value is 5, because in the range of [1,10], the function returns the input value itself, which is 5. The method of calling with named parameters is: clamp(min:=1,max:=10,value:=5). Note that the order of the parameters is not given in the default order, and the expression engine returns the calculation result correctly. .
Insert picture description here

Common functions

There are nearly 300 functions in QGIS expressions. Correctly using functions in expression construction can achieve a multiplier effect with less effort. Due to space limitations, this article cannot explain the functions one by one in detail. According to the degree of common use of the functions, about 30 functions are selected and explained in detail. The usage of other functions can be found in the help documentation of the expression builder.
Insert picture description here

Function typical application

darker(@symbol_color,130)

This function comes from "QGIS 3.10 Vector Style Settings" and is used to set the stroke color of power plant point features. darker is a color function that returns a darker color string. @symbol_color is the rendering color of the current geometry, and 130 is an integer corresponding to the darkening factor. This function implements the following functions: Return a color value that is 30% darker than @symbol_color.

maximum("passengers", group_by:="station_class")

Maximum is an aggregate function that returns the maximum value of the field or expression. "Passengers" is the number of passengers field in the attribute table, and "station_class" is the station type field. This function implements the following functions: group by station type and return the maximum number of passengers.

buffer( $geometry, 10 )

Buffer is a geometric figure function, which returns a geometric figure buffer according to a given radius. $geometry represents the currently selected geometric figure, 10 is the buffer radius, and its unit is the same as the map unit.

to_date('2020-07-29')

to_date is a date function that converts a string into a date object. The incoming parameters represent strings of different date forms. For the supported formats, please refer to the related documents of QGIS. By default, date strings are connected by dashes, year is represented by 4 digits, month is represented by 2 digits, and date It is represented by 2 digits, like '2020-07-29'.

format_date(now(),'yyyy-MM-dd')

format_date is a string function that implements formatting date fields and returns a custom string format. now() is a date function that returns the current date and time. The output result of this expression is the current date string connected by dashes, such as: '2020-07-29'.

summary

This article attempts to explore the understanding of functions in QGIS expressions from the aspects of system built-in functions, custom functions, use and search of functions, descriptions of commonly used functions and typical applications of functions. There are many types of functions in QGIS expressions, and the methods of use are flexible and changeable. This article is just a piece of advice. If there is a deviation in understanding, please correct me.


Wu Jianling

July 30, 2020


Copyright Notice


This article welcomes reprinting, please indicate the source when reprinting.


Insert picture description here

Guess you like

Origin blog.csdn.net/QGISClass/article/details/107706843