Actions — Add some custom buttons triggering PostgreSQL queries
Principle
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:
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.
Varoitus
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.
Vihje
For the project scope, the default database is used (file profiles.ini.php in the
configuration chapter.
Example action selector:
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
Prerequisites
Some knowledge in
SQLandJSONTo use the
selectcallback, your layer must have the selection enabled for the layer. See Attribute table — Configure the attribute table and the vector selectionThe layer must be published as WFS (see WFS/OAPI) and the primary key must be published as well in the Layer properties.
Configuring the tool
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.
Varoitus
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 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:
adds a new action,
edits the selected one (a double-click on the row works too),
the selected action can also be duplicated, removed
, or moved up
and down
: the order is the one used in the web interface,
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 (
layerandfeaturescopes) and the optional geometry to draw (projectandlayerscopes).Options: the additional parameters sent to the PostgreSQL function, with their default value. A number such as
500is 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
selectandredraw.
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
layerandfeaturescopes,an option cannot use the name of a parameter already sent by Lizmap Web Client, such as
feature_idorwkt. 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, atitle, ascope,layers, anicon, some optionaloptions, style,callbacksandconfirmproperty can be used.
An action can be proposed for a list of
layers: QGIS layer IDs should be used in thelayersarrayAn 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.
Each action is an object defined by:
a
namewhich is the action identifier. It must be unique in the file, and only contain letters, digits,_or-.a
titlewhich is used as a label in Lizmap interfacea
scopewhich can be:project,layerorfeaturean
iconwhich 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 (Media).an optional
confirmproperty, 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
descriptionproperty, providing a longer description of the action displayed in the selector panel (forprojectandlayerscopes). If not set, thetitleis displayed instead.an optional
geometryproperty, which activates a drawing tool in the interface when the action is selected (forprojectandlayerscopes). The user must draw a geometry before running the action; it is then automatically sent as thewktparameter to the PostgreSQL functionlizmap_get_data. Only single-part geometries can be drawn.an
optionsobject, 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
styleobject allowing to configure the returned geometry style. It follows OpenLayers styling attributes. The plugin handlesfill-color,stroke-color,stroke-width,circle-radius,circle-fill-color,circle-stroke-colorandcircle-stroke-width.a
callbacksobject allows to trigger some actions after the generated geometry is returned. They are defined by amethodname, which can at present be:zoom: zoom to the returned geometryselect: select the features from a given layer intersecting the returned geometry. The target layer QGIS internal ID must be added in thelayerIdproperty. In the example, the features of the layer containing buildings, IDbuilding_90f7692a_0ae2_4a7d_91de_b63cddb92963will be selected.redraw: redraw (refresh) a given layer in the map. The target layer QGIS ID must be added in thelayerIdproperty.
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
actionStartedwith the action properties,Lizmap backend checks if the action is well configured,
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)This query returns a GeoJSON which is then displayed on the map.
If some
callbackshave been configured, they are launched (selection,zoom,redraw)A Lizmap event
actionResultReceivedis 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
2592251664of the layerFire hydrantscorresponding 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 querylizmap_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.';
The function
lizmap_get_data(json)is provided here as an example. Since it is the key entry point, you need to adapt it to fit your needs. It aims to create a query for each action name, dynamically created for the given parameters, and return a GeoJSON representation of the query result data. You should have only one feature returned: use aggregation if needed. In the example above, we use theformatmethod to set the query text, and the functionquery_to_geojsonto return the GeoJSON for this query.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 ELSEclauses. See the content of theparametersvariable 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_projectthe action name
action_name, for examplebuffer_150. You should use a simple word with only letters, digits and_,the action scope
action_scope, for examplefeature,QGIS layer name (as in QGIS legend):
layer_name, for exampleFire hydrant, only forfeatureactions,the PostgreSQL table schema
layer_schemaand table namelayer_tablefor the layer, only forfeatureandlayerscoped actionsthe object feature id
feature_id, which corresponds to the value of the primary key field for the popup object, only forfeatureactions,the other properties given in the JSON configuration file, in the
optionsproperty, such asbuffer_sizewhich is150in the examplethe map center
map_centerand map extentmap_extent
The
IF ELSEis used to do a different query, built in thedatasourcevariable, by checking the action nameIf the return data contains a
messagefield, such as shown in the example above, the text contained in this field will be displayed in the map in a message bubble.The geometry returned by the function will be displayed on the map.
You could use your function to edit some data in your database, before returning a GeoJSON. To do so, you need to replace the
IMMUTABLEproperty withVOLATILE. Please USE IT WITH CARE !
Varoitus
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.
Katso myös
Chapter Adding your own JavaScript
For example, here we just write in the browser console the content received:
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);
}
});
You could use these data as you like in your JS code.