Adicionar o seu próprio código JavaScript

Princípio

Adding some JavaScript (JS) is useful for a variety of advanced usage. For instance, you can:

  • hide some UI elements that you don’t want to display by default

  • add a custom button in the UI

  • add a popup when the project is opened (to display funders, credits…)

  • avoid people being able to download elements of the page by right clicking on them, and of course much more.

Pré-requisitos

  • This function needs to be activated by the administrator of the Lizmap instance on the repository page.

  • The media directory. Read how to use Media folder in Lizmap.

Configuring the tool

  • In your repository (e.g. /home/data/repo1/myproject.qgs), you should have these directories:

    media
    |-- js
      |-- myproject
      |-- default
    
  • All the JavaScript code you copy in the /home/data/rep1/media/js/myproject/ directory will be executed by Lizmap for this specific project only.

  • All the JavaScript code in default will be executed for all projects.

  • To allow the execution of JavaScript code, in the Lizmap admin interface, you must add the privilege Allow themes for this repository.

Dica

It’s possible to temporary disable the loading of additional JavaScript by adding a parameter in the URL : &no_user_defined_js=1.

Video tutorial

This video is an quick start how to add a JavaScript to change the default panel in Lizmap.

Library of scripts

You can find some examples in the JavaScript library on GitHub.

Also, in the directory lizmap-web-client/lizmap/install/qgis/media/js/ (or in GitHub), you can find examples of suitable JavaScript code.

Remove the extension .example and copy them to your media/js/default/ folder to activate them.

API documentation

An automated generated documentation of the JavaScript API is available on docs.3liz.org.

Eventos Javascript disponíveis

O código Javascript pode utilizar muitos eventos despoletados pelo Lizmap Web Client. Aqui está uma lista de todos os eventos disponíveis, com as propriedades retornadas.

Eventos disponíveis no Lizmap Web Client

Nome do evento

Descrição

Propriedades retornadas

treecreated

Acionado quando a árvore da camada foi criada no painel de legenda

mapcreated

Acionado quando o mapa OpenLayers foi criado

layersadded

Acionado quando as camadas Openlayers foram adicionadas

uicreated

Acionado quando a interface foi criada

dockopened

Acionado quando um painel é aberto (painel esquerdo)

id

dockclosed

Acionado quando um painel é fechado (painel esquerdo)

id

minidockopened

Acionado quando uma mini-painel (recipiente direito para ferramentas) é aberto

id

minidockclosed

Acionado quando um mini-painel é fechado

id

bottomdockopened

Acionado quando o painel inferior é aberto

id

bottomdockclosed

Acionado quando o painel inferior é fechado

id

lizmapbaselayerchanged

Acionado quando um tema base foi alterado

camada

lizmapswitcheritemselected

Acionado quando uma camada foi destacada no painel de legenda de camadas

name | type | selected

layerstylechanged

Acionado quando um estilo de camada foi alterado

featureType

lizmaplocatefeaturecanceled

Acionado quando o utilizador cancelou a ferramenta localizar por camada

featureType

lizmaplocatefeaturechanged

Acionado quando o utilizador selecionou um item na ferramenta localizar por camada

featureType | featureId

lizmappopupdisplayed

Acionado quando o conteúdo popup é apresentado

lizmappopupallchildrendisplayed

Fired when the all children popups are displayed

parentPopupElement | childPopupElements

lizmappopupdisplayed_inattributetable

Acionado quando o conteúdo popup é apresentado na tabela de atributos (sub-painel direito)

lizmapeditionformdisplayed

Acionado quando um formulário de edição é apresentado

layerId | featureId | editionConfig

lizmapeditionfeaturecreated

Acionado quando um elemento de camada foi criado com a ferramenta de edição

layerId

lizmapeditionfeaturemodified

Acionado quando um elemento de camada foi modificado com a ferramenta de edição

layerId

lizmapeditionfeaturedeleted

Acionado quando um elemento de camada foi eliminado com a ferramenta de edição

layerId | featureId

attributeLayersReady

Acionado quando todas as camadas a serem presentadas na ferramenta de listar registos foram definidas

camadas

attributeLayerContentReady

Fired when a table for a layer has been displayed in the bottom dock. oTable is the DataTables API instance of the table

featureType | oTable

layerfeaturehighlighted

Acionado quando um elemento foi destacado na tabela de atributos (retângulo cinza). Acionar este evento manualmente força uma atualização das tabelas relacionadas se houver alguma para a camada atual

sourceTable | featureType | fid

layerfeatureselected

Acionar este evento para despoletar a seleção de um elemento numa camada, passando o ID do elemento. Após efetuada uma seleção, o evento layerSelectionChanged é acionado em retorno.

featureType | fid | updateDrawing

layerfeaturefilterselected

Acionar este evento para despoletar a filtragem de uma camada para os elementos selecionados. Deve selecionar alguns elementos antes de acionar este evento. Uma vez aplicado o filtro, o Lizmap aciona o evento layerFilteredFeaturesChanged em retorno.

featureType

layerFilteredFeaturesChanged

Acionado quando um filtro foi aplicado ao mapa para uma camada. Este evento também aciona o redesenhar do mapa e o conteúdo das tabelas de atributos.

featureType | featureIds | updateDrawing

layerFilterParamChanged

Acionado quando os parâmetros de pedido do WMS foram alterados para uma camada. Por exemplo, quando um ESTILO ou um FILTRO foi modificado para a camada.

featureType | filter | updateDrawing

layerfeatureremovefilter

Acionar este evento para remover qualquer filtro aplicado ao mapa. Uma vez executado, o evento layerFilteredFeaturesChanged é acionado de volta e o conteúdo do mapa e o conteúdo das tabelas de atributos são atualizados.

featureType

layerSelectionChanged

Acionado quando a seleção foi alterada para uma camada. Isto também aciona o redesenhar do mapa e a atualização do conteúdo da tabela de atributos

featureType | featureIds | updateDrawing

layerfeatureselectsearched

Fire this event to select all the features corresponding to the search of the attribute table (Search Builder), including features not displayed on the current page.

featureType | updateDrawing

layerfeatureunselectall

Acionar este evento para remover todos os elementos da seleção de uma camada. Uma vez executado, o Lizmap responde com o evento layerSelectionChanged

featureType | updateDrawing

lizmapexternalsearchitemselected

Fired when the user has selected an item listed in the results of the header search input

feature

actionStarted

Fired when a Lizmap action is triggered, just before the request is sent

action | layerId | featureId

actionResultReceived

Fired when a Lizmap popup action has been performed and the result has been received

layerId | featureId | action | features

Events of the main event dispatcher

Some events are fired by the main event dispatcher, lizMap.mainEventDispatcher. Use the lizMap.subscribe(listener, event) method to listen to them. Unlike lizMap.events.on, the listener is also called if the event has already been fired before the subscription, with the last event of this type. It is the recommended way to run some code when the interface is ready:

lizMap.subscribe(() => {
    // The user interface is fully loaded
    console.log('Lizmap is ready');
}, 'lizmap.uicreated');
Lizmap Web Client main event dispatcher events

Nome do evento

Descrição

lizmap.uicreated

Fired when the user interface is fully loaded

lizmap.modules.initialized

Fired when the Lizmap modules have been initialized

lizmap.locatebylayers.loaded

Fired when all the layers of the locate by layer tool have been loaded

Nota

The legacy uiready event is not fired anymore since Lizmap 3.10. Use lizmap.uicreated instead.

There are also some variables which are available.

Lizmap Web Client available variables

Variable name

Descrição

lizUrls.media

URL to get a media

lizUrls.params.repository

Name of the current repository

lizUrls.params.project

Name of the current project

lizMap.constants.MEDIA_REGEX

Regular expression to check if a path targets the Media folder

lizMap.constants.URL_REGEX

Regular expression to check if a string is an URL

Bootstrap 5

Since Lizmap 3.10, the user interface uses Bootstrap 5 instead of Bootstrap 2. If you have written some JavaScript adding HTML in the interface, or some CSS (read Criação de temas simples), you should check it:

  • Use the Bootstrap 5 attributes, such as data-bs-toggle, data-bs-target or data-bs-title.

  • Replace the Bootstrap 2 classes which have been removed, for instance pull-right by float-end, btn-mini or btn-small by btn-sm, close by btn-close…

  • The Bootstrap 2 icons icon-* are still available.

  • jQuery is still available.

The attribute table uses DataTables 2. Use the oTable property of the attributeLayerContentReady event to interact with a table.

Reprojection

Since Lizmap 3.10, lizMap.proj4 relies on proj4rs, written in Rust. It provides the main functions of proj4js: proj4(from, to, coordinates), proj4.defs, proj4.transform, proj4.toPoint and proj4.WGS84.

Exemplos

Legend API

For a given layer buildings :

var layer = lizMap.mainLizmap.state.rootMapGroup.getMapLayerByName('buildings');
// Name of the current loaded style
layer.wmsSelectedStyleName
// Toggle true or false the layer in the legend
layer.checked = true;

Please have a look to existing online demo, like the Paris by night

Simulate a click on the map

To simulate a click of the user on the map, for instance to display the popup at a given location, with coordinates in the map projection:

lizMap.mainLizmap.map.simulateClick([771083, 6279009]);

Disable right click

Add a file named e.g. disableRightClick.js with the following code:

lizMap.events.on({
   uicreated: function(e) {
      $('body').attr('oncontextmenu', 'return false;');
   }
});
  • If you want this code to be executed for all projects of your repository, you have to copy the file in the directory /home/data/rep1/media/js/default/ rather than in /home/data/rep1/media/js/myproject/.

Send current login user-ID

An example allowing you to send current login User-ID (and/or other user data) to PostgreSQL table column, using edition tool:

var formPrefix = 'jforms_view_edition';

// Name of the QGIS vector layer fields which must contain the user info
// In the list below, replace the right side by your own fields in Lizmap
var userFields = {
   login: 'your_lizmap_user_login_field',
   firstname: 'your_lizmap_user_firstname_field',
   lastname: 'your_lizmap_user_lastname_field'
};


lizMap.events.on({

   'lizmapeditionformdisplayed': function(e){

      // If user is logged in
      if( $('#info-user-login').length ){
            // Loop through the needed fields
            for( var f in userFields ){
               // If the user has some data for this property
               if( $('#info-user-' + f).text() ){
                  // If the field exists in the form
                  var fi = $('#' + formPrefix + '_' + userFields[f]);
                  if( fi.length ){
                        // Set val from lizmap user data
                        fi.val( $('#info-user-' + f).text() )
                        // Set disabled
                        fi.hide();
                  }
               }
            }
      }

   }

});

URL of a static file

If you want to get the URL of a static file, located in the Media folder:

var media = '/media/image/logo.jpg';
// It can also be a media located in the common media folder such as
// var media = '../media/logo.png';
var url = lizUrls.media + '?repository=' + lizUrls.params.repository + '&project=' + lizUrls.params.project + '&path=' + media;
// console.log(url);
var image  = '<img src="' + url + '" title="Logo" style="display:inline;height:80px;margin:20px 10px;" />';

It’s possible to use a function from the OpenLayers library to help building the URL :

var mediaUrl = OpenLayers.Util.urlAppend(
     lizUrls.media,
     OpenLayers.Util.getParameterString({
         "repository": lizUrls.params.repository,
         "project": lizUrls.params.project,
         "path": "picture.png"
     })
);