Actions — Add some custom buttons triggering PostgreSQL queries

定義

This module allows to add one or several actions in web interface. The concept has been inspired by QGIS actions, which can be used to run scripts inside QGIS.

Example of a feature action:

../../_images/publish-configuration-action-popup.gif

At present, the only engine for Lizmap actions is PostgreSQL queries (Python will not be supported). You can use PostgreSQL and PostGIS power to add specific logic in your web map.

警告

Lizmap actions are therefore different than QGIS native actions and are not compatible each other.

When the user clicks on an action button, a query is sent by Lizmap Web Client to the PostgreSQL database, with the current context data (map extent, feature ID, etc.).

A specific function lizmap_get_data is called with these parameters, and returns a GeoJSON response containing one or several features generated by the SQL query for the given action.

Lizmap Web Client will then run some callbacks from this response:

  • zoom or center to the returned geometry,

  • select features of another layer intersecting the returned geometry,

  • display a message, etc.

Three action scopes are supported :

  • project : an action menu item is added on the left menu bar when the map has at least one project action. The new panel shows an action selector and a button to trigger the selected action.

  • layer: the action selector is shown in the layer Informations panel visible by clicking the (i) button right the the layer name.

  • feature: action buttons are added in the popup toolbar for the layer features, allowing to trigger an action specific to each feature.

Tip

For the project scope, the default database is used (file profiles.ini.php in the configuration chapter.

Example action selector:

../../_images/action-selector.png

Demonstration

You can check the demo "Action and SQL" about fire hydrants on the demo website.

Click on a fire hydrant and

  • Either select buildings which are within 150m

  • Or find the closest fire station

‎前提条件‎

  • Some knowledge in SQL and JSON

  • To use the select callback, your layer must have the selection enabled for the layer. See Attribute table — Configure the attribute table and the vector selection

  • ‎レイヤーは WFS として公開する必要があり ( WFS/OAPI を参照)、主キーは 、同様に公開する必要があります。 :guilabel:` レイヤプロパティ ` で同様に公開する必要があります。‎

‎ツールの設定

The actions are stored in a specific JSON configuration file, placed aside the QGIS project in the same directory. This file lists the PostgreSQL actions to be added in the map.

The file is named like the QGIS project, with the .action extension: fire_hydrant_actions.qgs.action for the project fire_hydrant_actions.qgs. It must be sent to the server with the QGIS project and its Lizmap configuration file.

警告

In Lizmap 3.7, the JSON syntax has changed.

If you use the old JSON syntax, you will have a warning in Lizmap, inviting you to migrate to a newer version of the syntax. The Lizmap plugin cannot read the old syntax: the actions must be created again in the plugin.

With the plugin

The actions are configured in the The Lizmap logo Actions panel of the Lizmap plugin. The QGIS project must be saved first, so that the plugin knows where to write the action file.

The panel lists the actions of the file, with their name, title, scope and layers:

  • add_layer_svg adds a new action, edit_layer_svg edits the selected one (a double-click on the row works too),

  • the selected action can also be duplicated, removed remove_layer_svg, or moved up up_layer_svg and down down_layer_svg: the order is the one used in the web interface,

  • refresh_svg reads the action file again, for instance after editing it manually. Unsaved changes are lost.

The action dialog has four tabs:

  • General: the name, title, description, scope, icon and confirmation message of the action. Depending on the scope, choose the PostgreSQL layers where the action is available (layer and feature scopes) and the optional geometry to draw (project and layer scopes).

  • Options: the additional parameters sent to the PostgreSQL function, with their default value. A number such as 500 is written as a number, other values as text.

  • Style: the colors, widths and point radius used to draw the geometries returned by the action. A value which is not set is not written in the file.

  • Callbacks: the methods to run after the action, with the target layer for select and redraw.

The action file is written when the Lizmap configuration is saved, with the Apply or OK buttons, and only if the actions have been changed. If there is no action left, the action file is removed.

The plugin checks the actions, the errors are displayed below the list of actions and in the Checks panel:

  • the name must be unique in the file, with only letters, digits, _ or -,

  • the title and the icon are mandatory,

  • the layers must be PostgreSQL layers of the project, and at least one layer is needed for the layer and feature scopes,

  • an option cannot use the name of a parameter already sent by Lizmap Web Client, such as feature_id or wkt. The option names must start with a letter and only contain letters, digits or _.

An action with an error is a blocking check: the Lizmap configuration is not saved until the action is fixed. When a layer is removed from the QGIS project, it is also removed from the actions and their callbacks.

The JSON file

The file can still be written manually, for instance to read it or to version it with your project. When the plugin saves the file, the properties it does not handle are removed, such as a style attribute not listed below or an unknown callback method.

Each action is characterized by a name, a title, a scope, layers, an icon, some optional options,

style, callbacks and confirm property can be used.

  • An action can be proposed for a list of layers: QGIS layer IDs should be used in the layers array

  • An action can have a list of callbacks

Example of a JSON configuration file, name fire_hydrant_actions.qgs.action if the QGIS project file is named fire_hydrant_actions.qgs. In this project, there is a vector layer called Fire hydrants with the internal layer ID emergency_fire_hydrant_04132268_86fb_4d5e_a426_ce3133494091. You can get the QGIS layer internal ID with the QGIS expression @layer_id.

[
    {
        "name": "buffer_150",
        "title": "Buildings in the fire hydrant area (150m)",
        "scope": "feature",
        "layers": [
            "emergency_fire_hydrant_04132268_86fb_4d5e_a426_ce3133494091"
        ],
        "confirm": "Do you want to select buildings within 150m from this fire hydrant ?",
        "icon": "icon-home",
        "options": {
            "buffer_size": 150,
            "other_param": "yes"
        },
        "style": {
            "fill-color": "rgba(255,255,255,0.4)",
            "stroke-color": "#3399CC",
            "stroke-width": 1.25,
            "circle-radius": 5,
            "circle-fill-color": "rgba(255,255,255,0.4)",
            "circle-stroke-width": 1.25,
            "circle-stroke-color": "#3399CC"
        },
        "callbacks": [
            {
                "method": "zoom"
            },
            {
                "method": "select",
                "layerId": "building_90f7692a_0ae2_4a7d_91de_b63cddb92963"
            }
        ]
    },
    {
        "name": "closest_fire_station",
        "title": "Find the closest fire station from this fire hydrant",
        "scope": "feature",
        "layers": [
            "emergency_fire_hydrant_04132268_86fb_4d5e_a426_ce3133494091"
        ],
        "confirm": "Do you want to select the closest fire station from this fire hydrant ?",
        "icon": "icon-resize-small",
        "options": {},
        "style": {
            "stroke-color": "rgba(255,0,0,0.8)",
            "stroke-width": 4
        },
        "callbacks": [
            {
                "method": "zoom"
            },
            {
                "method": "select",
                "layerId": "stations_1a71d61f_cb99_4ac4_8bd4_86304af9be44"
            }
        ]
    }
]

The JSON configuration file lists the declared actions.

‎各 アクション は、次の式で定義されたオブジェクトです。‎

  • a name which is the action identifier. It must be unique in the file, and only contain letters, digits, _ or -.

  • ``title``‎は‎Lizmap インターフェイスのラベルとして使用されます

  • a scope which can be: project, layer or feature

  • an icon which is displayed on the action button (See the Bootstrap documentation). An SVG icon can be used instead of a bootstrap icon as a background of the popup action buttons. Use a relative media path (‎メディア‎).

  • an optional confirm property, containing some text. If set, a confirmation dialog will be shown to the user to ask if the action should really be launched or not. Use it if the action can modify some data in your database.

  • an optional description property, providing a longer description of the action displayed in the selector panel (for project and layer scopes). If not set, the title is displayed instead.

  • an optional geometry property, which activates a drawing tool in the interface when the action is selected (for project and layer scopes). The user must draw a geometry before running the action; it is then automatically sent as the wkt parameter to the PostgreSQL function lizmap_get_data. Only single-part geometries can be drawn.

  • an options object, giving some additional parameters for this action. You can add any needed parameters, except the ones already sent by Lizmap Web Client, listed in the next chapter (feature_id, wkt, etc.). The values are the default ones, a JavaScript script can replace them (see below).

  • a style object allowing to configure the returned geometry style. It follows OpenLayers styling attributes. The plugin handles fill-color, stroke-color, stroke-width, circle-radius, circle-fill-color, circle-stroke-color and circle-stroke-width.

  • ‎``callbacks`` オブジェクトは、生成されたgeometryが返された後に、いくつかのアクションを起動することができます。これらは method の名前で定義されています。‎

    • ‎``ズーム``:geometryにズームします。‎

    • select: select the features from a given layer intersecting the returned geometry. The target layer QGIS internal ID must be added in the layerId property. In the example, the features of the layer containing buildings, ID building_90f7692a_0ae2_4a7d_91de_b63cddb92963 will be selected.

    • ‎``再描画``:マップ内の特定のレイヤーを再描画(更新)します。ターゲットレイヤーQGIS IDは``layerId``プロパティに追加する必要があります。‎

How Lizmap uses this configuration file to launch actions

Lizmap detects the presence of this configuration file, and adds the needed logic when the map loads.

For example, for feature scoped actions, when the users clicks on an object of one of the action layer in the map, the popup panel shows the feature data. At the top of each popup item, a toolbar shows one button per each layer action. The action title will be displayed on hovering the action button.

Each button triggers the corresponding action, if it is not yet active (else it deactivates and erases the geometry in the map):

  • Lizmap Web Client emits a Lizmap events actionStarted with the action properties,

  • ‎Lizmapはバックエンドで、アクションが適切に設定されているかどうかをチェックします。‎

  • creates the PostgreSQL query SELECT public.lizmap_get_data(json) with the parameters written in JSON, and executes it in the layer PostgreSQL database. (See example below)

  • ‎このクエリは GeoJSON を返し、マップに表示されます。‎

  • If some callbacks have been configured, they are launched (selection, zoom, redraw)

  • A Lizmap event actionResultReceived is emitted with the returned data and action properties. This allow user-defined Javascript scripts to use the action results.

The created PostgreSQL query is built up by Lizmap Web Client and uses the PostgreSQL function lizmap_get_data(json) which must be created beforehand in the PostgreSQL table database. This function also uses a more generic function query_to_geojson(text) which transforms any PostgreSQL query string into a GeoJSON output.

Here is an example below of the query executed in the PostgreSQL database by Lizmap Web Client internally,

  • for the example configuration given above,

  • when the users clicks on the button action buffer_150,

  • for the feature with id 2592251664 of the layer Fire hydrants

  • corresponding to the PostgreSQL table fire_hydrant_actions.emergency_fire_hydrant:

SELECT public.lizmap_get_data('{
    "lizmap_repository": "features",
    "lizmap_project": "fire_hydrant_actions",
    "action_name": "buffer_150",
    "action_scope": "feature",
    "layer_name": "Fire hydrant",
    "layer_schema": "fire_hydrant_actions",
    "layer_table": "emergency_fire_hydrant",
    "feature_id": 2592251664,
    "map_center": "POINT(3.4345918 43.63399141565576)",
    "map_extent": "POLYGON((3.429635077741169 43.63175113378633,3.439548522258832 43.63175113378633,3.439548522258832 43.63623161401291,3.429635077741169 43.63623161401291,3.429635077741169 43.63175113378633))",
    "wkt": "",
    "buffer_size":150,
    "other_param": "yes"
}') AS data;

You can see that Lizmap creates a JSON parameter with all needed information and run the PostgreSQL function lizmap_get_data(json).

The current map extent and map center are also sent as parameters in WKT format (projection EPSG:4326) and can be used in the PostgreSQL function.

Mandatory PostgreSQL functions

You need to create this PostgreSQL functions:

  • query_to_geojson(text) which returns a valid GeoJSON text from any SELECT query

  • lizmap_get_data(json) which is the "control tower" of Lizmap actions: it creates a specific query for each action based on the parameters and then run the query and returns the GeoJSON

The following SQL code is an example to help you create the needed functions. Obviously, you must adapt them to fit your needs.

-- Returns a valid GeoJSON from any query
CREATE OR REPLACE FUNCTION query_to_geojson(datasource text)
RETURNS json AS
$$
DECLARE
    sqltext text;
    ajson json;
BEGIN
    sqltext:= format('
        SELECT jsonb_build_object(
            ''type'',  ''FeatureCollection'',
            ''features'', jsonb_agg(features.feature)
        )::json
        FROM (
          SELECT jsonb_build_object(
            ''type'',       ''Feature'',
            ''id'',         id,
            ''geometry'',   ST_AsGeoJSON(ST_Transform(geom, 4326))::jsonb,
            ''properties'', to_jsonb(inputs) - ''geom''
          ) AS feature
          FROM (
              SELECT * FROM (%s) foo
          ) AS inputs
        ) AS features
    ', datasource);
    RAISE NOTICE 'SQL = %s', sqltext;
    EXECUTE sqltext INTO ajson;
    RETURN ajson;
END;
$$
LANGUAGE 'plpgsql'
IMMUTABLE STRICT;

COMMENT ON FUNCTION query_to_geojson(text) IS 'Generate a valid GEOJSON from a given SQL text query.';

-- Create a query depending on the action, layer and feature and returns a GeoJSON.
CREATE OR REPLACE FUNCTION public.lizmap_get_data(parameters json)
RETURNS json AS
$$
DECLARE
    feature_id varchar;
    layer_name text;
    layer_table text;
    layer_schema text;
    action_name text;
    sqltext text;
    datasource text;
    ajson json;
BEGIN

    action_name:= parameters->>'action_name';
    feature_id:= (parameters->>'feature_id')::varchar;
    layer_name:= parameters->>'layer_name';
    layer_schema:= parameters->>'layer_schema';
    layer_table:= parameters->>'layer_table';

    -- Action buffer_150
    -- Performs a buffer on the geometry
    IF action_name = 'buffer_150' THEN
        datasource:= format('
            SELECT %1$s AS id,
            ''Buildings within 150m of the fire hydrant have been selected'' AS message,
            ST_Buffer(geom, 150) AS geom
            FROM %2$I.%3$I
            WHERE osm_id = %1$L -- `osm_id` is the field holding the unique identifier of each feature in this example layer
        ',
        feature_id,
        layer_schema,
        layer_table
        );
    ELSEIF action_name = 'closest_fire_station' THEN
        -- Draw a line to the closest fire station
        datasource:= format('
            WITH tmp_hydrant AS (
                SELECT geom FROM fire_hydrant_actions.emergency_fire_hydrant WHERE osm_id = %1$L
            )
            SELECT
                id, name, ST_Distance(hydrant.geom, stations.geom),
                ''The closest is :  '' || stations.name || '', '' || ST_Distance(hydrant.geom, stations.geom)::integer || ''m, flying air distance'' AS message,
                ST_MakeLine(stations.geom, hydrant.geom) AS geom,
                stations.id AS station_id
            FROM
                fire_hydrant_actions.stations stations,
                tmp_hydrant hydrant
            ORDER BY ST_Distance(hydrant.geom, stations.geom)
            LIMIT 1
        ',
        feature_id
        );
    ELSE
    -- Default : return geometry
        datasource:= format('
            SELECT
            %1$s AS id,
            ''The geometry of the object have been displayed in the map'' AS message,
            geom
            FROM %2$I.%3$I
            WHERE osm_id = %1$L
        ',
        feature_id,
        layer_schema,
        layer_table
        );

    END IF;

    SELECT query_to_geojson(datasource)
    INTO ajson
    ;
    RETURN ajson;
END;
$$
LANGUAGE 'plpgsql'
IMMUTABLE STRICT;

COMMENT ON FUNCTION public.lizmap_get_data(json) IS 'Generate a valid GeoJSON from an action described by a name, PostgreSQL schema and table name of the source data, a QGIS layer name, a feature id and additional options.';
  • ‎関数 lizmap_get_data(json) は、例としてここに示されています。 key entry point なので、ニーズに合わせて適応させる必要があります。 各アクション名のクエリを作成 をするために、指定されたパラメータに対して動的に作成され、クエリ結果データの GeoJSON 表現を返します。 1つの機能/地物 のみが返されている必要があります:必要に応じて集計を使用します。上記の例では、format``メソッドを使用してクエリテキストを設定し、関数 ``query_to_geojson を使用してこのクエリの GeoJSON を返します。‎

  • You can use all the given parameters (action name, source data schema and table name, feature id, QGIS layer name) to create the appropriate query for your action(s), by using the PostgreSQL IF THEN ELSIF ELSE clauses. See the content of the parameters variable in the example above, containing some of the JSON configuration file properties, and some properties of the QGIS layer:

    • Lizmap repository and project keys of the map: lizmap_repository & lizmap_project

    • the action name action_name, for example buffer_150. You should use a simple word with only letters, digits and _,

    • the action scope action_scope, for example feature,

    • QGIS layer name (as in QGIS legend): layer_name, for example Fire hydrant, only for feature actions,

    • the PostgreSQL table schema layer_schema and table name layer_table for the layer, only for feature and layer scoped actions

    • the object feature id feature_id, which corresponds to the value of the primary key field for the popup object, only for feature actions,

    • the other properties given in the JSON configuration file, in the options property, such as buffer_size which is 150 in the example

    • the map center map_center and map extent map_extent

  • ‎``IF ELSE``は アクション名 をチェックすることによって、datasource 変数に組み込まれた別のクエリを実行するために使用されます。‎

  • ‎上記の例のように、戻りデータに message フィールドが含まれている場合、このフィールドに含まれるテキストは吹き出しの **mapに表示**されます。‎

  • ‎関数によって返される geometry**は、 **マップ上に表示 されます‎

  • You could use your function to edit some data in your database, before returning a GeoJSON. To do so, you need to replace the IMMUTABLE property with VOLATILE. Please USE IT WITH CARE !

警告

Always use %L (literal) and %I (identifier) placeholders from PostgreSQL format() instead of manual string quoting with %s. When an argument must be embedded in a string expression, prefer concat(text, argument, text) to ensure proper escaping. Apply explicit type casting (e.g. ::integer) where appropriate. This prevents SQL injection when handling option values passed to the action.

Actions and user-defined JavaScript scripts

Actions can also be run from external JavaScript scripts: you can use the actions public methods to run an action, or reset the active action:

// Run an action
lizMap.mainLizmap.action.runLizmapAction(actionName, scope = 'feature', layerId = null, featureId = null, wkt = null);
// Reset the action
lizMap.mainLizmap.action.resetLizmapAction()

A WKT geometry, in EPSG:4326, can also be sent as an additional parameter. This is only possible when running the action with JavaScript. This allows to send a geometry to be used by the PostgreSQL action function lizmap_get_data as a property of the parameters SQL variable. (for example to get data from another table with geometries intersecting this passed WKT geometry)

Additional custom parameters can be passed from JavaScript via the options object. Each key must correspond to a parameter declared in the .action configuration file — any unknown key will be silently ignored and never forwarded to the SQL function.

If a key is present in the configuration but omitted from the options object, the default value defined in the .action file is used as a fallback.

For security reasons, a value containing some SQL keywords (such as insert or drop) is ignored: the default value is used instead, and a message is written in the Lizmap admin log.

 // Run an action with options
lizMap.mainLizmap.action.runLizmapAction(
    actionName, scope = 'feature', layerId = null, featureId = null, wkt = null,
    options = {
        "my_param": someJsVariable,
        "other_param": "static_value"
    }
);

Since Lizmap Web Client triggers an event actionResultReceived any time the user clicks on an action button, and data is returned (in the same time as the result geometry is drawn on the map), you could use your own JavaScript code to add some logic after the result is shown.

参考

‎章‎ ‎javaスクリプトの追加‎

‎たとえば、ここでは、コンテンツが受信したブラウザコンソールに書き込みます。‎

lizMap.events.on({

    actionResultReceived: function(e) {
        // QGIS Layer id
        var layerId = e.layerId;
        console.log('Layer ID = ' + layerId);
        // Feature ID, which means the value of the primary key field
        var featureId = e.featureId;
        console.log('Feature ID = ' + featureId);
        // Action item with its name and other properties: name, title, options, styles, etc.
        var action = e.action;
        console.log('Action properties = ');
        console.log(action);
        // Features returned by the action
        var features = e.features;
        console.log('Returned object = ');
        console.log(features);
    }
});

‎これらのデータは、JS コードで自由に使用できます。‎