14.2.

レイヤデータや付属関数、ユーザー定義関数を基に、 は属性値やジオメトリ、変数を操作するための強力な手段を提供します。これにより次のようなことが可能になります。動的にジオメトリスタイルを変更する、ラベルの内容や位置を変更する、ダイアグラムの値を変更する、レイアウトアイテムの高さを変更する、幾つかの地物を選択する、仮想フィールドを作成する、等々。

14.2.1. 式文字列ビルダー

式を組み立てるための主要なダイアログである 式文字列ビルダー は、QGISの多くの部分から使用することができますが、特に以下のような時に使うことができます。

式ビルダーダイアログから以下のタブにアクセス可能です。

  • [式]タブ これは、事前に定義された関数のリストのおかげで、使用する式を作成し、チェックするのに役立ちます。

  • [関数エディタ]タブ これは、カスタムの関数を作成することで、関数のリストを拡張するのに役立ちます。

式の使用例:

  • フィールド計算機から、既存の「total_pop」と「area_km2」フィールドを使用して、「pop_density」フィールドを計算します:

    "total_pop" / "area_km2"
    
  • 「pop_density」の値に応じてフィールド「density_level」のカテゴリを更新します:

    CASE WHEN "pop_density" < 50 THEN 'Low population density'
         WHEN "pop_density" >= 50 and "pop_density" < 150 THEN 'Medium population density'
         WHEN "pop_density" >= 150 THEN 'High population density'
    END
    
  • Update a region layer field with the names (comma separated) of contained airports:

    aggregate('airport_layer', 'concatenate', "name", within($geometry, geometry(@parent)), ', ')
    
  • 住宅の平均価格が平方メートル当たり10000€より小さいか大きいかに応じて、すべての地物に分類したスタイルを適用します:

    "price_m2" > 10000
    
  • 「式で選択...」ツールを使用して、「高人口密度」エリアに相当し、加えて平方メートルあたりの住宅の平均価格が10000€よりも高くなるエリアのすべての地物を選択します:

    "density_level" = 'High population density' and "price_m2" > 10000
    

    同様にこの式は、どの地物にラベルを付すべきか、あるいはどの地物を地図中に表示すべきかを定義するためにも使用できるでしょう。

式を使用することによって可能性が大きく広がります。

ちなみに

式を読みやすくするために名前付きパラメータを使用する

関数によっては多くのパラメータを設定する必要があります。式エンジンは名前付きパラメータの使用をサポートしています。つまり clamp(1, 2, 9) と式を書くのではなく、パラメータの意味を明示して clamp( min:=1, value:=2, max:=9) と書くことができるということです。これは例えば clamp( value:=2, max:=9, min:=1) のように、引数の位置を入れ替えることも可能にします。名前付きパラメータを使用すると、式関数の引数が参照するものを明確にできます。これは式に書かれたものを後々になってから読み解こうとするときに役立ちます。

14.2.2. 関数のリスト

タブは、関数やレイヤのフィールドやその値を使って、式を書くための主要なインターフェイスを提供します。タブには以下のウィジェットが含まれています。

  • 式エディタエリアでは、式を入力したりペーストしたりします。入力を早めるために自動補完が使えるようになっています。

    • 入力したテキストに応じた変数名、関数名、フィールド名が下に表示されます。 Up 矢印キーと Down 矢印キーを使って項目間を移動することができます。式に挿入するには Tab キーを押すか、挿入したい項目を単にクリックします。

    • Function parameters are shown while filling them.

    QGIS also checks the expression rightness and highlights all the errors using:

    • Underline: for unknown functions, wrong or invalid arguments;

    • Marker: for every other error (eg, missing parenthesis, unexpected character) at a single location.

    ちなみに

    Document your expression with comments

    When using complex expression, it is good practice to add text either as a multiline comment or inline comments to help you remember.

    /*
    Labels each region with its highest (in altitude) airport(s)
    and altitude, eg 'AMBLER : 264m' for the 'Northwest Artic' region
    */
    with_variable(
      'airport_alti', -- stores the highest altitude of the region
      aggregate(
        'airports',
        'max',
        "ELEV", -- the field containing the altitude
        -- and limit the airports to the region they are within
        filter := within( $geometry, geometry( @parent ) )
      ),
        aggregate( -- finds airports at the same altitude in the region
          'airports',
          'concatenate',
          "NAME",
          filter := within( $geometry, geometry( @parent ) )
            and "ELEV" = @airport_alti
        )
        || ' : ' || @airport_alti || 'm'
        -- using || allows regions without airports to be skipped
    )
    
  • Under the expression editor, an Output preview displays the result of the expression evaluated on the first feature of the layer. In case of error, it indicates it and you can access details with the provided hyperlink.

  • A function selector displays the list of functions, variables, fields... organized in groups. A search box is available to filter the list and quickly find a particular function or field. Double-clicking an item adds it to the expression editor.

  • A help panel displays help for each selected item in the function selector.

    ちなみに

    Press Ctrl+Click when hovering a function name in an expression to automatically display its help in the dialog.

    A field's values widget shown when a field is selected in the function selector helps to fetch features attributes. Double-clicking a value adds it to the expression editor.

    ちなみに

    The right panel, showing functions help or field values, can be collapsed (invisible) in the dialog. Press the Show Values or Show Help button to get it back.

../../../_images/function_list.png

図 14.65 [式]タブ

14.2.2.1. 集計関数

このグループには、レイヤーやフィールドの値を集約する関数が含まれています。

関数

説明

集計

別のレイヤーの地物を使用して計算された集計値を返します

array_agg

Returns an array of aggregated values from a field or expression

collect

Returns the multipart geometry of aggregated geometries from an expression

concatenate

Returns all aggregated strings from a field or expression joined by a delimiter

concatenate_unique

Returns all unique aggregated strings from a field or expression joined by a delimiter

count

マッチする地物の数を返します

count_distinct

重複しない値の数を返します

count_missing

欠損(null)値の数を返します

iqr

フィールドまたは式から計算された四分位範囲を返します

majority

フィールドまたは式から最頻値(最も多く出現する値)を返します

max_length

フィールドまたは式から文字列の最大長を返します

maximum

フィールドまたは式から最大値を返します

mean

フィールドまたは式から平均値を返します

median

フィールドまたは式から中央値を返します

min_length

フィールドまたは式から文字列の最小長を返します

minimum

フィールドまたは式から最小値を返します

minority

フィールドまたは式から最少頻値(最も少なく出現する値)を返します

q1

フィールドまたは式から計算された第1四分位数を返します

q3

フィールドまたは式から計算された第3四分位数を返します

range

フィールドまたは式から値の範囲(最大値-最小値)を返します

relation_aggregate

レイヤー関係からマッチする子地物を使用して計算された集計値を返します

stdev

フィールドまたは式から標準偏差の値を返します

sum

フィールドまたは式から合計値を返します

例:

  • 「station_class」フィールドでグループ化されたレイヤー中の地物から「乗客」フィールドの最大値を返します:

    maximum("passengers", group_by:="station_class")
    
  • 現在の地図帳地物内部の駅に対する合計乗降客数を計算:

    aggregate('rail_stations','sum',"passengers",
      intersects(@atlas_geometry, $geometry))
    
  • レイヤーから「my_relation」の関係を使用して、一致するすべての子のために「field_from_related_table」フィールドの平均値を返します:

    relation_aggregate('my_relation', 'mean', "field_from_related_table")
    

    または:

    relation_aggregate(relation:='my_relation', aggregate := 'mean',
      expression := "field_from_related_table")
    

14.2.2.2. Array Functions

This group contains functions to create and manipulate arrays (also known as list data structures). The order of values within the array matters, unlike the 'map' data structure, where the order of key-value pairs is irrelevant and values are identified by their keys.

関数

説明

array

Returns an array containing all the values passed as parameter

array_all

Returns true if an array contains all the values of a given array

array_append

Returns an array with the given value added at the end

array_cat

Returns an array containing all the given arrays concatenated

array_contains

Returns true if an array contains the given value

array_distinct

Returns an array containing distinct values of the given array

array_filter

Returns an array with only the items for which an expression evaluates to true

array_find

Returns the index (0 for the first one) of a value within an array. Returns -1 if the value is not found.

array_first

Returns the first value of an array

array_foreach

Returns an array with the given expression evaluated on each item

array_get

Returns the Nth value (0 for the first one) of an array

array_insert

Returns an array with the given value added at the given position

array_intersect

Returns true if any element of array_1 exists in array_2

array_last

Returns the last element of an array

array_length

Returns the number of elements of an array

array_prepend

Returns an array with the given value added at the beginning

array_remove_all

Returns an array with all the entries of the given value removed

array_remove_at

Returns an array with the given index removed

array_reverse

Returns the given array with array values in reversed order

array_slice

Returns the values of the array from the start_pos argument up to and including the end_pos argument

array_sort

Returns the provided array with its elements sorted

array_to_string

Concatenates array elements into a string separated by a delimiter and using optional string for empty values

generate_series

Creates an array containing a sequence of numbers

regexp_matches

Returns an array of all strings captured by capturing groups, in the order the groups themselves appear in the supplied regular expression against a string

string_to_array

Splits string into an array using supplied delimiter and optional string for empty values

14.2.2.3. 色関数

このグループには、色を操作するための関数が含まれています。

関数

説明

color_cmyk

そのシアン、マゼンタ、イエロー、ブラックの成分に基づいて色の文字列表現を返します

color_cmyka

そのシアン、マゼンタ、イエロー、ブラック及びアルファ(透明度)成分に基づいて色の文字列表現を返します

color_grayscale_average

Applies a grayscale filter and returns a string representation from a provided color

color_hsl

その色相、彩度、明度属性に基づく色の文字列表現を返します

color_hsla

その色相、彩度、明度及びアルファ(透明度)属性に基づいて色の文字列表現を返します

color_hsv

その色相、彩度、および値属性に基づいて色の文字列表現を返します

color_hsva

その色相、彩度、値およびアルファ(透明度)の属性に基づいて、色の文字列表現を返します

color_mix_rgb

Returns a string representing a color mixing the red, green, blue, and alpha values of two provided colors based on a given ratio

color_part

赤色成分またはアルファ成分例えば、色文字列から特定の成分を返します

color_rgb

その赤、緑、青の成分に基づいて色の文字列表現を返します

color_rgba

その赤、緑、青、及びアルファ(透明度)成分に基づいて色の文字列表現を返します

create_ramp

Returns a gradient ramp from a map of color strings and steps

darker

より暗い(または明るい)色文字列を返します

lighter

より明るい(または暗い)色文字列を返します

project_color

プロジェクトの色スキーマから色を返します

ramp_color

色ランプから色を表す文字列を返します

set_color_part

赤色成分またはアルファ成分、例えば、色文字列の特定の色成分を設定します

14.2.2.4. Conditional Functions

このグループには式の中で条件を扱う関数を含まれます.

関数

説明

CASE ... THEN ... END

式を評価し、真の場合は結果を返します。複数の条件をテストできます

CASE WHEN ... THEN ... ELSE ... END

式を評価し、それが真か偽かどうかで異なる結果を返します。複数の条件をテストできます

coalesce

式リストから最初の非NULL値を返します

if

条件をテストし、条件付きのチェックに応じて、異なる結果を返します

nullif(value1, value2)

Returns a null value if value1 equals value2 otherwise it returns value1. This can be used to conditionally substitute values with NULL.

try

Tries an expression and returns its value if error-free, an alternative value (if provided) or Null if an error occurs

いくつかの例:

  • 最初の条件がtrueである場合は値を戻し、そうでない場合は別の値を:

    CASE WHEN "software" LIKE '%QGIS%' THEN 'QGIS' ELSE 'Other' END
    

14.2.2.5. 変換関数

このグループは、別の(整数にする例えば、文字列、文字列の整数)に1つのデータ型を変換する関数が含まれています。

関数

説明

to_date

日付オブジェクトに文字列を変換します

to_datetime

DateTimeオブジェクトに文字列を変換します

to_dm

Converts a coordinate to degree, minute

to_dms

Converts coordinate to degree, minute, second

to_int

数を文字列を整数に変換します

to_interval

間隔型に文字列を変換します(日付の日、時間、月、などを取るために使用できます)

to_real

実際の文字列を数値に変換します

to_string

数値を文字列に変換します

to_time

時間オブジェクトに文字列を変換します

14.2.2.6. カスタム関数

このグループは、ユーザーが作成した関数が含まれています。詳細については 関数エディタ を参照。

14.2.2.7. 日付と時刻の関数

このグループには日付や時刻データを扱う関数が含まれます.

関数

説明

age

2つの日付または日付時刻の間の差を時間間隔として返します

day

日付または日時、または間隔からの日数から日を抽出します

day_of_week

指定した日付または日時の曜日に対応する番号を返します

epoch

Returns the interval in milliseconds between the unix epoch and a given date value

hour

日時または時刻からの時間、または間隔から時間数を抽出します

minute

日時または時刻から分を、または間隔から分数を抽出します

month

間隔から数ヶ月の日付または日時、または数字から月の部分を抽出します

now

現在の日付と時刻を返します

second

日時または時刻から秒を、または間隔からの秒数を抽出します

week

日付または日時から週数を、または間隔から週数を抽出します

year

Extracts the year part from a date or datetime, or the number of years from an interval

このグループはまた、 変換関数 (TO_DATE、TO_TIME、to_datetime、to_interval)と 文字列関数 (format_date)グループといくつかの関数を共有します。

いくつかの例:

  • 「month_number /年」の形式で、今日の月と年を取得します。

    format_date(now(),'MM/yyyy')
    -- Returns '03/2017'
    

これらの関数に加えて、 - (マイナス)演算子を使用して日付、日付時刻または時刻を減算すると間隔を返します。

 + (プラス)、 - (マイナス)演算子を使用して、間隔を日付、日付時刻または時刻に加算または減算すると、日時を返します。

  • QGIS 3.0リリースまでの日数を取得します。

    to_date('2017-09-29') - to_date(now())
    -- Returns <interval: 203 days>
    
  • 時間と同じ:

    to_datetime('2017-09-29 12:00:00') - to_datetime(now())
    -- Returns <interval: 202.49 days>
    
  • 今から100日の日時を取得します。

    now() + to_interval('100 days')
    -- Returns <datetime: 2017-06-18 01:00:00>
    

注釈

フィールドに日付と日時との間隔を保存する

The ability to store date, time and datetime values directly on fields may depend on the data source's provider (e.g., Shapefile accepts date format, but not datetime or time format). The following are some suggestions to overcome this limitation:

  • 日付日時時間to_format() 関数を使用した後、テキスト形式のフィールドに記憶できます。

  • 間隔 は日付抽出関数のいずれかを使用した後に整数または小数タイプフィールドに記憶できます(例えば、日数で表される時間間隔を取得する day()

14.2.2.8. フィールドと値

レイヤーからのフィールドのリストが含まれています。

Double-click a field name to have it added to your expression. You can also type the field name (preferably inside double quotes) or its alias.

To retrieve fields values to use in an expression, select the appropriate field and, in the shown widget, choose between 10 Samples and All Unique. Requested values are then displayed and you can use the Search box at the top of the list to filter the result. Sample values can also be accessed via right-clicking on a field.

To add a value to the expression you are writing, double-click on it in the list. If the value is of a string type, it should be simple quoted, otherwise no quote is needed.

14.2.2.9. Files and Paths Functions

This group contains functions which manipulate file and path names.

関数

説明

base_file_name

Returns the base name of the file without the directory or file suffix.

file_exists

Returns true if a file path exists.

file_name

Returns the name of a file (including the file extension), excluding the directory.

file_path

Returns the directory component of a file path, without the file name

file_size

Returns the size (in bytes) of a file.

file_suffix

Returns the file extension from a file path.

is_directory

Returns true if a path corresponds to a directory.

is_file

Returns true if a path corresponds to a file.

14.2.2.10. ファジー・マッチング関数

このグループには、値間でファジィ比較をするための関数が含まれています。

関数

説明

hamming_distance

入力文字列内で対応する位置にあり、文字が異なっている文字の数を返します

levenshtein

別の文字列を変更するために必要な文字の編集(挿入、削除または置換)の最小数を返します。二つの文字列間の類似性を測定します

longest_common_substring

二つの文字列間の最長共通部分文字列を返します

soundex

文字列のSoundexの表現を返します

14.2.2.11. 一般関数

This group contains general assorted functions.

関数

説明

env

Gets an environment variable and returns its content as a string. If the variable is not found, NULL will be returned.

eval

Evaluates an expression which is passed in a string. Useful to expand dynamic parameters passed as context variables or fields.

is_layer_visible

Returns true if a specified layer is visible

layer_property

レイヤーまたはそのメタデータの値のプロパティを返します。これは、レイヤー名、CRS、ジオメトリタイプ、地物数...が可能です

var

Returns the value stored within a specified variable. See 変数 below

with_variable

Creates and sets a variable for any expression code that will be provided as a third argument. Useful to avoid repetition in expressions where the same value needs to be used more than once.

14.2.2.12. ジオメトリ関数

This group contains functions that operate on geometry objects (e.g. buffer, transform, $area).

関数

説明

$area

現在の地物の領域サイズを返します

$geometry

現在の地物のジオメトリを返します(他の関数と一緒に処理のために使用できます)

$length

現在のライン地物の長さを返します

$perimeter

現在のポリゴン地物の周囲を返します

$x

Returns the X coordinate of the current feature

$x_at(n)

Returns the X coordinate of the nth node of the current feature's geometry

$y

Returns the Y coordinate of the current feature

$y_at(n)

Returns the Y coordinate of the nth node of the current feature's geometry

angle_at_vertex

折れ線の幾何学上の指定された頂点のジオメトリに二等分角(平均角度)を返します。角度は北から時計回りの度です

area

ジオメトリポリゴン地物の面積を返します。計算はこのジオメトリの空間参照系で実行されます

azimuth

北を基準して時計回りに測定されたpoint_aからpoint_bへの方位をラジアン単位の角度で返します.

boundary

Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the geometry - see also Boundary).

bounds

Returns a geometry which represents the bounding box of an input geometry. Calculations are in the Spatial Reference System of this geometry (see also Bounding boxes)

bounds_height

ジオメトリのバウンディングボックスの高さを返します。計算はこのジオメトリの空間参照系で実行されます

bounds_width

ジオメトリのバウンディングボックスの幅を返します。計算はこのジオメトリの空間参照系で実行されます

buffer

Returns a geometry that represents all points whose distance from this geometry is less than or equal to distance. Calculations are in the Spatial Reference System of this geometry (see also Buffer)

buffer_by_m

Creates a buffer along a line geometry where the buffer diameter varies according to the M values at the line vertices (see also Variable width buffer (by M value))

centroid

Returns the geometric center of a geometry (see also 重心)

closest_point

第二のジオメトリに最も近いジオメトリ上の点を返します

collect_geometries

Collects a set of geometries into a multi-part geometry object (see also Collect geometries)

combine

2つのジオメトリの組み合わせを返します

contains(a,b)

bのどの点のaの外部にはなく、かつbの内部の少なくとも1つの点がaの内部に存在するの場合かつ場合にのみ戻り値1(真)

convex_hull

Returns the convex hull of a geometry (this represents the minimum convex geometry that encloses all geometries within the set) (see also Convex hull)

crosses

与えられたジオメトリが、いくつかの、全てではない、内部点を共通して持っている場合、値1(真)を返します

difference(a,b)

Returns a geometry that represents that part of geometry a that does not intersect with geometry b (see also Difference)

disjoint

ジオメトリが一緒に任意の空間を共有していない場合は1(true)を返します

distance

投影単位での2つのジオメトリ間の(空間参照系に基づく)最小距離を返します

distance_to_vertex

指定された頂点までのジオメトリに沿った距離を返します

end_point

Returns the last node from a geometry (see also Extract specific vertices)

extend

Extends the start and end of a linestring geometry by a specified amount (see also Extend lines)

exterior_ring

ジオメトリがポリゴンでない場合、ラインポリゴンジオメトリの外部リングを表す文字列、またはnullを返します

extrude(geom,x,y)

Returns an extruded version of the input (Multi-) Curve or (Multi-)Linestring geometry with an extension specified by X and Y

flip_coordinates

Returns a copy of the geometry with the X and Y coordinates swapped (see also Swap X and Y coordinates)

force_rhr

Forces a geometry to respect the Right-Hand-Rule (see also Force right-hand-rule)

geom_from_gml

ジオメトリのGML表現から作成されたジオメトリを返します

geom_from_wkt

well-knownテキスト(WKT)表現から作成されたジオメトリを返します

geom_to_wkt

SRIDメタデータなしでジオメトリのwell-knownテキスト(WKT)表現を返します

geometry

地物のジオメトリを返します

geometry_n

ジオメトリコレクションからn番目のジオメトリを、入力ジオメトリがコレクションでない場合はnullを返します

hausdorff_distance

Returns basically a measure of how similar or dissimilar two geometries are, with a lower distance indicating more similar geometries

inclination

Returns the inclination measured from the zenith (0) to the nadir (180) on point_a to point_b

interior_ring_n

ポリゴンジオメトリからn番目の内部リングの形状を、ジオメトリがポリゴンでない場合はnullを返します

intersection

Returns a geometry that represents the shared portion of two geometries (see also Intersection)

intersects

ジオメトリが別と交差するかどうかをテストします。ジオメトリが空間的に交差する(スペースの任意の部分を共有する)場合 1(真)を、それらがしない場合0を返します

intersects_bbox

ジオメトリのバウンディングボックスが別のジオメトリのバウンディングボックスに重なるかどうかをテストします。ジオメトリのバウンディングボックスが空間的に交差する場合はtrueを、そうでない場合はfalseを返します

is_closed

ラインストリングが閉じている(開始点と終了点が一致している)場合はtrue、ラインストリングが閉じていない場合はfalse、ジオメトリがラインストリングでない場合はnullを返します

length

ラインジオメトリ地物(または文字列の長さ)の長さを返します

line_interpolate_angle

ラインストリングジオメトリに沿って指定された距離でジオメトリに平行な角度を返します。角度は度で北から時計回りです。

line_interpolate_point

Returns the point interpolated by a specified distance along a linestring geometry. (see also Interpolate point on line)

line_locate_point

ラインストリングは、指定されたポイントジオメトリに来る最も近い位置に対応したラインストリングに沿った距離を返します。

line_merge

入力ジオメトリから任意の接続ラインストリングは、単一の折れ線にマージされている(マルチ)ラインストリングジオメトリを返します。

line_substring

Returns the portion of a line or curve geometry falling betweeen specified start and end distances (measured from the beginning of the line) (see also Line substring)

m

Returns the M value of a point geometry

make_circle

Creates a circular geometry based on center point and radius

make_ellipse

Creates an elliptical geometry based on center point, axes and azimuth

make_line

Creates a line geometry from a series or an array of point geometries

make_point(x,y,z,m)

Returns a point geometry from X and Y (and optional Z or M) values

make_point_m(x,y,m)

Returns a point geometry from X and Y coordinates and M values

make_polygon

外リングおよび任意一連の内リングのジオメトリからポリゴンのジオメトリを作成します

make_rectangle_3points

Creates a rectangle from 3 points

make_regular_polygon

Creates a regular polygon

make_square

Creates a square from a diagonal

make_triangle

Creates a triangle polygon

minimal_circle

Returns the minimal enclosing circle of an input geometry (see also Minimum enclosing circles)

nodes_to_points

Returns a multipoint geometry consisting of every node in the input geometry (see also Extract vertices)

num_geometries

入力ジオメトリがコレクションでない場合はジオメトリコレクションにジオメトリの数を返し、またはnull

num_interior_rings

入力ジオメトリがポリゴンまたはコレクションでない場合は、多角形またはジオメトリコレクション内の内部リングの数、またはnullを返します

num_points

ジオメトリの頂点の数を返します

num_rings

入力ジオメトリがポリゴンまたはコレクションでない場合は、多角形またはジオメトリコレクション内の(外部リングを含む)リングの数、またはnullを返します

offset_curve

Returns a geometry formed by offsetting a linestring geometry to the side. Distances are in the Spatial Reference System of this geometry. (see also Offset lines)

order_parts

与えられた基準によってマルチジオメトリの部分を並べ替えます

oriented_bbox

Returns a geometry representing the minimal oriented bounding box of an input geometry (see also Oriented minimum bounding box)

overlaps

ジオメトリが別と重なるかどうかをテストします。ジオメトリが空間を共有し、同じ寸法のものであるが、互いに完全に含まれていない場合、値1(真)を返します

perimeter

ジオメトリポリゴン地物の周囲を返します。計算はこのジオメトリの空間参照系であります

point_n

Returns a specific node from a geometry (see also Extract specific vertices)

point_on_surface

Returns a point guaranteed to lie on the surface of a geometry (see also Point on Surface)

pole_of_inaccessibility

Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface (see also Pole of inaccessibility)

project

Returns a point projected from a start point using a distance, a bearing (azimuth) and an elevation in radians (see also Project points (Cartesian))

relate

二つのジオメトリ間の関係の次元拡張9交差モデル(DE-9IM)表現を試験または返します

reverse

Reverses the direction of a line string by reversing the order of its vertices (see also Reverse line direction)

segments_to_lines

Returns a multi line geometry consisting of a line for every segment in the input geometry (see also Explode lines)

shortest_line

2つのジオメトリを結ぶ最短ラインを返します。結果として得られるラインは、ジオメトリ1で開始し、ジオメトリ2で終了します

simplify

Simplifies a geometry by removing nodes using a distance based threshold (see also Simplify)

simplify_vw

Simplifies a geometry by removing nodes using an area based threshold (see also Simplify)

single_sided_buffer

Returns a geometry formed by buffering out just one side of a linestring geometry. Distances are in the Spatial Reference System of this geometry (see also Single sided buffer)

smooth

Smooths a geometry by adding extra nodes which round off corners in the geometry (see also Smooth)

start_point

Returns the first node from a geometry (see also Extract specific vertices)

sym_difference

Returns a geometry that represents the portions of two geometries that do not intersect (see also 対称差)

tapered_buffer

Creates a buffer along a line geometry where the buffer diameter varies evenly over the length of the line (see also Tapered buffers)

touches

ジオメトリが別のジオメトリに触れるかどうかをテストします。それらのジオメトリが少なくとも1つの共通点を持っているがその内部が交差していない場合、値1(真)を返します

transform

Returns the geometry transformed from the source CRS to the destination CRS (see also Reproject layer)

translate

Returns a translated version of a geometry. Calculations are in the Spatial Reference System of the geometry (see also Translate)

union

ジオメトリの点集合を表現するジオメトリを返します

wedge_buffer

Returns a wedge shaped buffer originating from a point geometry given an angle and radii (see also Create wedge buffers)

within (a,b)

ジオメトリが別のジオメトリ内にあるかどうかをテストします。ジオメトリaが完全にジオメトリbの内部にある場合に1(true)を返します

x

Returns the X coordinate of a point geometry, or the X coordinate of the centroid for a non-point geometry

x_max

Returns the maximum X coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

x_min

Returns the minimum X coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

y

Returns the Y coordinate of a point geometry, or the Y coordinate of the centroid for a non-point geometry

y_max

Returns the maximum Y coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

y_min

Returns the minimum Y coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

z

Returns the Z coordinate of a point geometry

いくつかの例:

  • Return the X coordinate of the current feature's centroid:

    x( $geometry )
    
  • 地物の面積に応じた値を送り返す:

    CASE WHEN $area > 10 000 THEN 'Larger' ELSE 'Smaller' END
    
  • You can manipulate the current geometry using the variable $geometry to create a buffer or get a point on the geometry's surface:

    buffer( $geometry, 10 )
    point_on_surface( $geometry )
    
  • Given a point feature, generate a closed line (using make_line) around the point's geometry:

    make_line(
      -- using an array of points placed around the original
      array_foreach(
        -- list of angles for placing the projected points (every 90°)
        array:=generate_series( 0, 360, 90 ),
        -- translate the point 20 units in the given direction (angle)
        expression:=project( $geometry, distance:=20, azimuth:=radians( @element ) )
      )
    )
    

14.2.2.13. Layout Functions

This group contains functions to manipulate print layout items properties.

関数

説明

item_variables

Returns a map of variables from a layout item inside this print layout

An example:

  • Get the scale of the 'Map 0' in the current print layout:

    map_get( item_variables('Map 0'), 'map_scale')
    

14.2.2.14. Map Layers

This group contains a list of the available layers in the current project. This offers a convenient way to write expressions referring to multiple layers, such as when performing aggregates, attribute or spatial queries.

It also provides some convenient functions to manipulate layers.

関数

説明

decode_uri

Takes a layer and decodes the uri of the underlying data provider. Available information depends on the data provider type.

14.2.2.15. Maps Functions

This group contains functions to create or manipulate keys and values of map data structures (also known as dictionary objects, key-value pairs, or associative arrays). Unlike the list data structure where values order matters, the order of the key-value pairs in the map object is not relevant and values are identified by their keys.

関数

説明

from_json

Loads a json-formatted string

hstore_to_map

Creates a map from a hstore-formatted string

json_to_map

Creates a map from a json-formatted string

map

Returns a map containing all the keys and values passed as pair of parameters

map_akeys

Returns all the keys of a map as an array

map_avals

Returns all the values of a map as an array

map_concat

Returns a map containing all the entries of the given maps. If two maps contain the same key, the value of the second map is taken.

map_delete

Returns a map with the given key and its corresponding value deleted

map_exist

Returns true if the given key exists in the map

map_get

Returns the value of a map, given it's key

map_insert

Returns a map with an added key/value

map_to_hstore

Merges map elements into a hstore-formatted string

map_to_json

Merges map elements into a json-formatted string

to_json

Creates a json-formatted string from a map, an array or other value

14.2.2.16. 数学関数

このグループは、数学関数(例えば、平方根、sinとcos)が含まれています。

関数

説明

abs

数値の絶対値を返します

acos

ラジアン単位で値の逆余弦を返します

asin

ラジアンで値の逆正弦を返します

atan

Returns the inverse tangent of a value in radians

atan2(y,x)

Returns the inverse tangent of Y/X by using the signs of the two arguments to determine the quadrant of the result

azimuth(a,b)

点aの点bへの垂直から時計回りに測定されたラジアン単位の角度として北基準の方位を返します

ceil

数を上向きに丸めます

clamp

入力値を指定された範囲へ制限します

cos

Returns the cosine of an angle in radians

degrees

ラジアンから度に変換

exp

値の指数を返します

floor

数を下向きに丸めます

inclination

Returns the inclination measured from the zenith (0) to the nadir (180) on point_a to point_b.

ln

渡された式の自然対数を返します

log

渡された値とベースでの対数の値を返します

log10

渡された式の10を底とする対数の値を返します

max

Returns the largest not null value in a set of values

min

Returns the smallest not null value in a set of values

pi

計算のためのパイの値を返します

radians

度からラジアンに変換します

rand

最小値と最大値の引数で指定された範囲内(最小最大を含む)のランダムな整数を返します

randf

最小値と最大値の引数で指定された範囲内(最小最大を含む)のランダムな浮動小数点数を返します

round

小数点以下の桁数に丸めます

scale_exp

指数曲線を使用して、出力範囲への入力領域から所定の値を変換します

scale_linear

線形補間を使用して、出力範囲への入力領域から所定の値を変換します

sin

Returns the sine of an angle in radians

sqrt

値の平方根を返します

tan

Returns the tangent of an angle in radians

14.2.2.17. 演算子

このグループには演算子が含まれています(例えば、+、 - 、*)。以下の数学関数のほとんどについて、入力の一つがNULLである場合は結果はNULLであることに注意してください。

関数

説明

a + b

二つの値の加算(a足すb)

a - b

二つの値の減算(a引くb)。

a * b

2つの値の乗算(a掛けるb)

a / b

2つの値の除算(a割るb)

a % b

bで割った余り(例えば、7%2 = 1、または2は7から3回とれて残りが1)

a ^ b

二つの値(例えば、2 ^ 2 = 4または8 = 2 ^ 3)

a < b

2つの値を比較し、左の値が右の値未満である場合は1と評価します(aはbよりも小さいです)

a <= b

Compares two values and evaluates to 1 if the left value is less than or equal to the right value

a <> b

2つの値を比較し、それらが等しくない場合は1と評価します

a = b

2つの値を比較し、それらが等しい場合は1と評価します

a != b

aとbは等しくありません

a > b

(aがbよりも大きい)2つの値を比較し、左の値が右の値よりも大きい場合に1と評価

a >= b

2つの値を比較し、左の値が右の値以上である場合は1と評価

a ~ b

aは正規表現bと一致します

||

2つの値を1つの文字列へと結合します。値のいずれかがNULLの場合、結果はNULLになります

'\n'

文字列に改行を挿入します

LIKE

最初のパラメーターは、供給されたパターンと一致した場合に1を返します

ILIKE

第1のパラメーターは、大文字と小文字を区別しない供給されるパターンと一致する場合に返す(ILIKEが一致大文字と小文字を区別しないを作る代わりに等を使用できます)

a IS b

二つの値が同一であるかどうかをテストします。aがbと同じである場合は1を返します

a OR b

条件aまたはbが真である場合に1を返します

a AND b

条件aとbが該当する場合に1を返します

NOT

条件を否定

"Column_name"

Value of the field Column_name, take care to not be confused with simple quote, see below

'string'

文字列の値、二重引用符と混同しないように注意してください。上記を参照してください。

NULL

null値

a IS NULL

aは値なし

a IS NOT NULL

aは値を持っています

a IN (値[,値])

aはリストされた値を下回っています

a NOT IN (値[,値])

aはリストされた値を下回りません

いくつかの例:

  • 文字列と列名の値を結合します:

    'My feature''s id is: ' || "gid"
    
  • Test if the "description" attribute field starts with the 'Hello' string in the value (note the position of the % character):

    "description" LIKE 'Hello%'
    

14.2.2.18. Processing Functions

This group contains functions that operate on processing algorithms.

関数

説明

parameter

Returns the value of a processing algorithm input parameter

14.2.2.19. Rasters Functions

This group contains functions to operate on raster layer.

関数

説明

raster_statistic

Returns statistics from a raster layer

raster_value

Returns the raster band value at the provided point

14.2.2.20. Record and Attributes Functions

このグループにはレコードを特定するような関数が含まれます.

関数

説明

$currentfeature

現在の地物が評価されて返します。これは、現在の地物から属性値を評価するために、「属性」関数を使用できます。

$id

現在の行の地物IDを返します。

attribute

地物から指定された属性の値を返します

attributes

Returns a map of all attributes from a feature, with field names as map keys

get_feature

指定された属性値に一致するレイヤーの最初の地物を返します

get_feature_by_id

Returns the feature of a layer matching the given feature ID

is_selected

Returns if a feature is selected

num_selected

Returns the number of selected features on a given layer

represent_value

Returns the configured representation value for a field value (convenient with some widget types)

sql_fetch_and_increment

Manage autoincrementing values in SQLite databases

uuid

各行の汎用一意識別子(UUID)を生成します。各UUIDは38文字です。

いくつかの例:

  • フィールド「ID」が現在の地物のフィールド「名前」と同じ値を有するレイヤー「LayerA」の最初の地物を返します(jointureの一種):

    get_feature( 'layerA', 'id', attribute( $currentfeature, 'name') )
    
  • 前の例から結合された地物の面積を計算します:

    area( geometry( get_feature( 'layerA', 'id', attribute( $currentfeature, 'name') ) ) )
    

14.2.2.21. 文字列関数

このグループには文字列を操作する関数が含まれています(置き換え、大文字に変換、など)。

関数

説明

char

Unicodeのコードに関連付けられた文字を返します

concat

複数の文字列を1つに連結します

format

指定された引数を使用して文字列をフォーマットします

format_date

カスタム文字列形式に日付型や文字列をフォーマットします

format_number

千の桁区切りでフォーマットされた数を返します(また、供給された桁数に数値を切り捨て)

left(string, n)

文字列のn個の左端の文字が含まれている部分文字列を返します

length

戻り値文字列の長さ(またはライン形状地物の長さ)

lower

小文字に文字列を変換します

lpad

Returns a string padded on the left to the specified width, using the fill character

regexp_match

Returns the first matching position matching a regular expression within a string, or 0 if the substring is not found

regexp_replace

置き換え付属の正規表現で文字列を返します

regexp_substr

付属の正規表現にマッチする文字列の一部を返します

replace

Returns a string with the supplied string, array, or map of strings replaced by a string, an array of strings or paired values

right(string, n)

文字列のn個の右端の文字を含む文字列を返します

rpad

Returns a string padded on the right to the specified width, using the fill character

strpos

Returns the first matching position of a substring within another string, or 0 if the substring is not found

substr

文字列の一部を返します

title

文字列のすべての単語をタイトルケース(先頭大文字ですべての単語の小文字)に変換します

trim

文字列からすべての先頭と末尾の空白(スペース、タブなど)を削除します

upper

文字列aを大文字に変換します

wordwrap

Returns a string wrapped to a maximum/minimum number of characters

フィールド連結について

You can concatenate strings or field values using either || or + operators or the concat function, with some special characteristics:

  • The + operator also means sum up expression, so if you have an integer (field or numeric value) operand, this can be error prone and you better use the others:

    'My feature''s id is: ' + "gid" => triggers an error as gid is an integer
    
  • When any of the arguments is a NULL value, either || or + will return a NULL value. To return the other arguments regardless the NULL value, you may want to use the concat function:

    "country_name" || NULL => NULL
    concat('My feature''s id is: ', NULL) => My feature's id is
    concat("firstname", "nickname", "lastname") => Chuck Norris (if empty nickname)
    "firstname" + "nickname" + "lastname" => NULL (if one field is empty)
    
  • For other cases, do at your convenience:

    'My country is ' + "country_name" + ' (' + "country_code" + ')'
    'My country is ' || "country_name" || ' (' || "country_code" || ')'
    concat('My country is ', "country_name", ' (', "country_code", ')')
    # All the above return: My country is France (FR)
    

14.2.2.22. 変数

This group contains dynamic variables related to the application, the project file and other settings. The availability of variables depends on the context:

  • expressionSelect 式で選択 ダイアログから使用

  • calculateField フィールド計算機 ダイアログから使用

  • レイヤーのプロパティダイアログから使用

  • 印刷レイアウトから使用

To use these variables in an expression, they should be preceded by the @ character (e.g, @row_number).

関数

説明

algorithm_id

The unique ID of an algorithm

atlas_feature

The current atlas feature (as feature object)

atlas_featureid

The current atlas feature ID

atlas_featurenumber

The current atlas feature number in the layout

atlas_filename

The current atlas file name

atlas_geometry

The current atlas feature geometry

atlas_layerid

The current atlas coverage layer ID

atlas_layername

The current atlas coverage layer name

atlas_pagename

The current atlas page name

atlas_totalfeatures

The total number of features in atlas

canvas_cursor_point

The last cursor position on the canvas in the project's geographical coordinates

cluster_color

The color of symbols within a cluster, or NULL if symbols have mixed colors

cluster_size

The number of symbols contained within a cluster

current_feature

The feature currently being edited in the attribute form or table row

current_geometry

The geometry of the feature currently being edited in the form or the table row

fullextent_maxx

Maximum x value from full canvas extent (including all layers)

fullextent_maxy

Maximum y value from full canvas extent (including all layers)

fullextent_minx

Minimum x value from full canvas extent (including all layers)

fullextent_miny

Minimum y value from full canvas extent (including all layers)

geometry_part_count

The number of parts in rendered feature's geometry

geometry_part_num

The current geometry part number for feature being rendered

geometry_point_count

The number of points in the rendered geometry's part

geometry_point_num

The current point number in the rendered geometry's part

grid_axis

The current grid annotation axis (eg, 'x' for longitude, 'y' for latitude)

grid_number

The current grid annotation value

item_id

The layout item user ID (not necessarily unique)

item_uuid

The layout item unique ID

layer

The current layer

layer_id

The ID of current layer

layer_name

The name of current layer

layout_dpi

The composition resolution (DPI)

layout_name

The layout name

layout_numpages

The number of pages in the layout

layout_page

The page number of the current item in the layout

layout_pageheight

The active page height in the layout (in mm)

layout_pagewidth

The active page width in the layout (in mm)

legend_column_count

The number of columns in the legend

legend_filter_by_map

Indicates if the content of the legend is filtered by the map

legend_filter_out_atlas

Indicates if the atlas is filtered out of the legend

legend_split_layers

Indicates if layers can be split in the legend

legend_title

The title of the legend

legend_wrap_string

The character(s) used to wrap the legend text

map_crs

The Coordinate reference system of the current map

map_crs_acronym

The acronym of the Coordinate reference system of the current map

map_crs_definition

The full definition of the Coordinate reference system of the current map

map_crs_description

The name of the Coordinate reference system of the current map

map_crs_ellipsoid

The acronym of the ellipsoid of the Coordinate reference system of the current map

map_crs_proj4

The Proj4 definition of the Coordinate reference system of the current map

map_crs_wkt

The WKT definition of the Coordinate reference system of the current map

map_extent

The geometry representing the current extent of the map

map_extent_center

The point feature at the center of the map

map_extent_height

The current height of the map

map_extent_width

The current width of the map

map_id

The ID of current map destination. This will be 'canvas' for canvas renders, and the item ID for layout map renders

map_layer_ids

The list of map layer IDs visible in the map

map_layers

The list of map layers visible in the map

map_rotation

The current rotation of the map

map_scale

The current scale of the map

map_units

The units of map measurements

notification_message

Content of the notification message sent by the provider (available only for actions triggered by provider notifications).

parent

Refers to the current feature in the parent layer, providing access to its attributes and geometry when filtering an aggregate function

project_abstract

The project abstract, taken from project metadata

project_area_units

The area unit for the current project, used when calculating areas of geometries

project_author

The project author, taken from project metadata

project_basename

The basename of current project's filename (without path and extension)

project_creation_date

The project creation date, taken from project metadata

project_crs

The Coordinate reference system of the project

project_crs_arconym

The acronym of the Coordinate reference system of the project

project_crs_definition

The full definition of the Coordinate reference system of the project

project_crs_description

The description of the Coordinate reference system of the project

project_crs_ellipsoid

The ellipsoid of the Coordinate reference system of the project

project_crs_proj4

The Proj4 representation of the Coordinate reference system of the project

project_crs_wkt

The WKT (well known text) representation of the coordinate reference system of the project

project_distance_units

The distance unit for the current project, used when calculating lengths of geometries and distances

project_ellipsoid

The name of the ellipsoid of the current project, used when calculating geodetic areas or lengths of geometries

project_filename

The filename of the current project

project_folder

The folder of the current project

project_home

The home path of the current project

project_identifier

The project identifier, taken from the project's metadata

project_keywords

The project keywords, taken from the project's metadata

project_last_saved

Date/time when project was last saved.

project_path

The full path (including file name) of the current project

project_title

The title of current project

project_units

The units of the project's CRS

qgis_locale

The current language of QGIS

qgis_os_name

The current Operating system name, eg 'windows', 'linux' or 'osx'

qgis_platform

The QGIS platform, eg 'desktop' or 'server'

qgis_release_name

The current QGIS release name

qgis_short_version

The current QGIS version short string

qgis_version

The current QGIS version string

qgis_version_no

The current QGIS version number

row_number

現在の行の番号を格納します

snapping_results

Gives access to snapping results while digitizing a feature (only available in add feature)

scale_value

The current scale bar distance value

symbol_angle

The angle of the symbol used to render the feature (valid for marker symbols only)

symbol_color

The color of the symbol used to render the feature

symbol_count

The number of features represented by the symbol (in the layout legend)

symbol_id

The Internal ID of the symbol (in the layout legend)

symbol_label

The label for the symbol (either a user defined label or the default autogenerated label - in the layout legend)

user_account_name

The current user's operating system account name

user_full_name

The current user's operating system user name

value

The current value

with_variable

Allows setting a variable for usage within an expression and avoid recalculating the same value repeatedly

いくつかの例:

  • Return the X coordinate of a map item center in layout:

    x( map_get( item_variables( 'map1'), 'map_extent_center' ) )
    
  • Return, for each feature in the current layer, the number of overlapping airport features:

    aggregate( layer:='airport', aggregate:='count', expression:="code",
                   filter:=intersects( $geometry, geometry( @parent ) ) )
    
  • Get the object_id of the first snapped point of a line:

    with_variable(
      'first_snapped_point',
      array_first( @snapping_results ),
      attribute(
        get_feature_by_id(
          map_get( @first_snapped_point, 'layer' ),
          map_get( @first_snapped_point, 'feature_id' )
        ),
        'object_id'
      )
    )
    

14.2.2.23. 最近の関数

This group contains recently used functions. Depending on the context of its usage (feature selection, field calculator, generic), recently applied expressions are added to the corresponding list (up to ten expressions), sorted from more to less recent. This makes it easy to quickly retrieve and reapply previously used expressions.

14.2.3. 関数エディタ

関数エディタ タブでは、Python言語を使ってユーザ独自の関数を書くことができます。これにより、事前定義関数ではカバーされない特定のニーズに対処するための、手軽で快適な手段を手に入れることができます。

../../../_images/function_editor.png

図 14.66 [関数エディタ] タブ

新しい関数を作成するには次のようにします。

  1. signPlus 新規ファイル ボタンをクリックします。

  2. フォームがポップアップしますので、使用する名前を入力して OK をクリックします。

    入力した名前の新しい項目が Function Editor タブの左側のパネルに追加されます。これはQGISのテンプレートから生成されたPython .py ファイルです。このファイルは現在有効になっている ユーザープロファイル のディレクトリ配下の /python/expressions フォルダに格納されます。

  3. 右側のパネルはファイルの内容を表示します。最初はテンプレートのPythonスクリプトが表示されていますので、このコードやヘルプを必要に応じて書き換えてください。

  4. start 関数の保存と読み込み ボタンをクリックします。あなたの書いた関数が タブの関数ツリーの中に追加されます。デフォルトでは Custom グループの中に追加されます。

  5. 新しい関数をお楽しみください。

  6. 関数に改善が必要なときは、 関数エディタ タブに戻って修正を加えた後、再度 start 関数の保存と読み込み ボタンをクリックしてファイルに変更を反映させてください。 これにより式タブにも変更が反映されます。

カスタムPython関数はユーザープロファイルのディレクトリ配下に格納されます。QGISが起動するごとに、現在のユーザープロファイルの下で定義されたすべての関数が自動的に読み込まれます。新しい関数は /python/expressions フォルダの中にのみ保存されて、プロジェクトファイルには保存されないことに注意してください。カスタム関数を使用したプロジェクトを共有するときは、 /python/expressions フォルダの .py ファイルも共有する必要があります。.

独自関数がどのように作成されるかの簡単な例を見てもらいます。

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

@qgsfunction(args='auto', group='Custom')
def my_sum(value1, value2, feature, parent):
    """
    Calculates the sum of the two parameters value1 and value2.
    <h2>Example usage:</h2>
    <ul>
      <li>my_sum(5, 8) -> 13</li>
      <li>my_sum("field1", "field2") -> 42</li>
    </ul>
    """
    return value1 + value2

この簡単な例では、2つの値を扱う my_sum 関数を作成しています。args='auto' を使用した場合、その関数で必須となる引数の数は、Python中で定義された関数の引数から2を引いた数(featureparent を引いた数)になります。

この関数は次のようにして式の中で使うことができます。

../../../_images/customFunction.png

図 14.67 式タブに追加されたカスタム関数

Pythonコードの作成に関する詳しい情報は PyQGIS 開発者用 Cookbook で見つけることができます。