22. Working with OGC / ISO protocols

O Consórcio Geoespacial Aberto (OGC), é uma organização internacional como mais de 300 organizações em todo mundo do tipo comerciais, sem fins lucrativos e de investigação. Os membros desenvolvem e implementam padrões para os conteúdos e serviços geoespaciais, processamento e troca de dados SIG.

Describing a basic data model for geographic features, an increasing number of specifications are developed by OGC to serve specific needs for interoperable location and geospatial technology, including GIS. Further information can be found at https://www.ogc.org/.

Importantes especificações OGC suportadas pelo QGIS são:

OGC services are increasingly being used to exchange geospatial data between different GIS implementations and data stores. QGIS can deal with the above specifications as a client, being SFS (through support of the PostgreSQL / PostGIS data provider, see section Camadas PostGIS).

You can also share your maps and data through the WMS, WMTS, WFS, WFS-T and WCS protocols using a webserver with QGIS Server, UMN MapServer or GeoServer installed.

22.1. Cliente WMS/WMTS

22.1.1. Visão Global do Suporte WMS

QGIS currently can act as a WMS client that understands WMS 1.1, 1.1.1 and 1.3 servers. In particular, it has been tested against publicly accessible servers such as DEMIS.

A WMS server acts upon requests by the client (e.g., QGIS) for a raster map with a given extent, set of layers, symbolization style, and transparency. The WMS server then consults its local data sources, rasterizes the map, and sends it back to the client in a raster format. For QGIS, this format would typically be JPEG or PNG.

WMS is generically a REST (Representational State Transfer) service rather than a full-blown Web service. As such, you can actually take the URLs generated by QGIS and use them in a web browser to retrieve the same images that QGIS uses internally. This can be useful for troubleshooting, as there are several brands of WMS server on the market and they all have their own interpretation of the WMS standard.

As camadas WMS podem ser adicionadas facilmente, desde que conheça o acesso URL para o servidor WMS, tenha uma ligação de serviço a esse servidor, e o servidor compreenda HTTP como um mecanismos de transporte de dados.

Additionally, QGIS will cache your WMS responses (i.e. images) for 24h as long as the GetCapabilities request is not triggered. The GetCapabilities request is triggered every time the Connect button in the WMS/WMTS dialog is used to retrieve the WMS server capabilities. This is an automatic feature meant to optimize project loading time. If a project is saved with a WMS layer, the corresponding WMS tiles will be loaded from the cache the next time the project is opened as long as they are not older than 24h.

22.1.2. Visão Global do Suporte WMTS

QGIS can also act as a WMTS client. WMTS is an OGC standard for distributing tile sets of geospatial data. This is a faster and more efficient way of distributing data than WMS because with WMTS, the tile sets are pre-generated, and the client only requests the transmission of the tiles, not their production. A WMS request typically involves both the generation and transmission of the data. A well-known example of a non-OGC standard for viewing tiled geospatial data is Google Maps.

De maneira a exibir os dados a várias escalas perto do que o utilizador queira ver, os conjuntos de mosaicos WMTS são produzidos em vários diferentes níveis de escala e são disponibilizados para o cliente SIG a seu pedido.

Este diagrama ilustra o conceito dos conjuntos de mosaicos

../../../_images/concept_wmts.png

Fig. 22.1 Conceito dos conjuntos de mosaicos do WMTS

The two types of WMTS interfaces that QGIS supports are via Key-Value-Pairs (KVP) and RESTful. These two interfaces are different, and you need to specify them to QGIS differently.

  1. In order to access a WMTS KVP service, a QGIS user must open the WMS/WMTS interface and add the following string to the URL of the WMTS tile service:

    "?SERVICE=WMTS&REQUEST=GetCapabilities"
    

    An example of this type of address is:

    https://opencache.statkart.no/gatekeeper/gk/gk.open_wmts?service=WMTS&request=GetCapabilities
    

    A camada topo2 funciona lindamente para testar neste WMTS. Adicionando esta linha e texto indica que é um serviço web WMTS que deverá ser usado em vez de o serviço WMS.

  2. O serviço WMTS RESTful torna-se uma forma diferente, é um URL simples, a forma recomendada pela OGC é:

    {WMTSBaseURL}/1.0.0/WMTSCapabilities.xml
    

    This format helps you to recognize that it is a RESTful address. A RESTful WMTS is accessed in QGIS by simply adding its address in the WMS setup in the URL field of the form. An example of this type of address for the case of an Austrian basemap is:

    https://maps.wien.gv.at/basemap/1.0.0/WMTSCapabilities.xml
    

Nota

You can still find some old services called WMS-C. These services are quite similar to WMTS (i.e., same purpose but working a little bit differently). You can manage them the same as you do WMTS services. Just add ?tiled=true at the end of the url. See https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification for more information about this specification.

Quando lê o WMTS pode muitas vezes pensar em WMS-C.

22.1.3. Selecionando os Servidores WMS/WMTS

The first time you use the WMS/WMTS feature in QGIS, there are no servers defined.

You then need to create connections to the server you are targeting:

  1. Go to the wms WMS/WMTS tab of the Data Source Manager dialog, either by:

    • clicking the dataSourceManager Open Data Source Manager button (or pressing Ctrl+L) and enabling the tab

    • clicking the addWmsLayer Add WMS layer button on the Manage Layers toolbar

    • or selecting Layer ► Add Layer ► addWmsLayer Add WMS/WMTS Layer… menu

  2. Press New from the Layers tab. The Create a New WMS/WMTS Connection… dialog appears.

    Dica

    Right-click the wms WMS/WMTS entry from within the Browser panel and select New Connection… also opens the Create a New WMS/WMTS Connection… dialog.

  3. Em seguida, digite os parâmetros para se conectar ao seu servidor WMS desejado, conforme listado abaixo:

    ../../../_images/add_connection_wms.png

    Fig. 22.2 Criando uma conexão com um servidor WMS

    • Name: A name for the connection. This name will be used in the Server Connections drop-down box so that you can distinguish it from other WMS servers.

    • URL: URL of the server providing the data. This must be a resolvable host name – the same format as you would use to open a telnet connection or ping a host, i.e. the base URL only. For example, you shouldn’t have fragments such as request=GetCapabilities or version=1.0.0 in your URL.

    • Authentication (optional): using a stored configuration or a basic authentication with Username and Password.

      Aviso

      Entering username and password in the Authentication tab will keep unprotected credentials in the connection configuration. Those credentials will be visible if, for instance, you shared the project file with someone. Therefore, it’s advisable to save your credentials in an Authentication configuration instead (Configurations tab). See Sistema de Autenticação for more details.

    • HTTP Referência

    • DPI-Mode: Available options are all, off, QGIS, UMN and GeoServer

    • unchecked Ignore GetMap/GetTile/GetLegendGraphic URI reported in capabilities: if checked, use given URI from the URL field above.

    • unchecked Ignore GetFeatureInfo URI reported in capabilities: if checked, use given URI from the URL field above.

    • unchecked Ignorar a orientação dos eixos (WMS 1.3/WMTS)

    • unchecked Ignore reported layer extents: because the extent reported by raster layers may be smaller than the actual area which can be rendered (notably for WMS servers with symbology which takes more space than the data extent), check this option to avoid cropping raster layers to their reported extents, resulting in truncated symbols on the borders of these layers.

    • unchecked Inverter orientação do eixo

    • unchecked Suavizar transformação do mapa de pixels

  4. Pressione OK

Once the new WMS/WMTS server connection has been created, it will be preserved for future QGIS sessions.

If you need to set up a proxy server to be able to receive WMS services from the internet, you can add your proxy server in the options. Choose Settings ► Options and click on the Network tab. There, you can add your proxy settings and enable them by setting checkbox Use proxy for web access. Make sure that you select the correct proxy type from the Proxy type selectString drop-down menu.

22.1.4. Carregando as camadas WMS/WMTS

Once you have successfully filled in your parameters, you can use the Connect button to retrieve the capabilities of the selected server. This includes the image encoding, layers, layer styles and projections. Since this is a network operation, the speed of the response depends on the quality of your network connection to the WMS server. While downloading data from the WMS server, the download progress is visualized in the lower left corner of the main QGIS dialog.

Your screen should now look a bit like Fig. 22.3, which shows the response provided by a WMS server.

../../../_images/connection_wms.png

Fig. 22.3 Dialog for adding a WMS server, with filter on available layers

The upper part of the Layers tab of the dialog shows a tree structure that can include layer groups embedding layers with their associated image style(s) served by the server. Each item can be identified by:

  • um ID

  • um Nome

  • um Título

  • e um Resumo.

A lista pode ser filtrada usando a ferramenta de |pesquisa| no canto superior direito.

Codificação da Imagem

A seção Codificação de Imagem agora apresenta uma lista de formatos suportados pelo cliente e servidor. Escolha de acordo com as exigências de precisão da sua imagem.

Dica

Codificação da Imagem

Tipicamente irá encontrar servidores WMS que oferecem a escolha da codificação de imagem JPEG ou PNG. O JPEG é um formato de perda de compressão, enquanto que o PNG reprodução fielmente os dados raster brutos.

Use JPEG se espera dados WMS para fotografia na natureza e/ou não se importa da perda de alguma qualidade na imagem. Este típico trade-off reduz em 5 vezes o requerimento de transferência comparado ao PNG.

Use o PNG se necessitar representações precisas dos dados originais, e não se importa dos requerimentos de transferência de dados.

Opções

The Options area of the dialog provides means to configure the WMS requests. You can define:

  • Tile size if you want to set tile sizes (e.g., 256x256) to split up the WMS request into multiple requests.

  • Request step size: if you want to reduce the effect of cut labels at tile borders, increasing the step size creates larger requests, fewer tiles and fewer borders. The default value is 2000.

  • The Maximum number of GetFeatureInfo results from the server

  • Each WMS layer can be presented in multiple CRSs, depending on the capability of the WMS server. If you select a WMS from the list, a field with the default projection provided by the web server appears. Press the setProjection Select CRS widget to replace the default projection of the WMS with another CRS supported by the WMS server.

    A dialog similar to the one shown in Fig. 10.3 will appear. The main difference with the WMS version of the dialog is that only those CRSs supported by the WMS server will be shown.

  • Finally you can activate checkbox Use contextual WMS Legend if the WMS Server supports this feature. Then only the relevant legend for your current map view extent will be shown and thus will not include legend items for items you can’t see in the current map.

At the bottom of the dialog, a Layer name text field displays the selected item’s Title. You can change the name at your will. This name will appear in the Layers panel after you pressed the Add button and loaded the layer(s) in QGIS.

You can select several layers at once, but only one image style per layer. When several layers are selected, they will be combined at the WMS server and transmitted to QGIS in one go, as a single layer. The default name is a slash (/) separated list of their original title. You can however opt to checkbox Load as separate layers.

Ordem das Camadas

The Layer Order tab lists the selected layers available from the current connected WMS server.

WMS layers rendered by a server are overlaid in the order listed in the Layers tab, from top to bottom of the list. If you want to change the overlay order, you can use the Up and Down buttons of the Layer Order tab.

Transparência

The Global transparency setting from the Layer Properties is hard coded to be always on, where available.

22.1.5. Mosaicos

When using WMTS (Cached WMS) services you are able to browse through the Tilesets tab given by the server. Additional information like tile size, formats and supported CRS are listed in this table.

# example of WMTS service

https://opencache.statkart.no/gatekeeper/gk/gk.open_wmts?service=WMTS&request=GetCapabilities

Selecting a layer to load, it is also possible to apply an Interpretation method, converting it into a raster layer of single band float type, ready for styling using QGIS usual raster renderers.

In combination with this feature, you can use the tile scale slider by selecting View ► Panels ( or kde Settings ► Panels), then choosing Tile Scale Panel. This gives you the available scales from the tile server with a nice slider docked in.

22.1.6. Usando a Ferramenta Identificar

Once you have added a WMS server, and if any layer from a WMS server is queryable, you can then use the identify Identify tool to select a pixel on the map canvas. A query is made to the WMS server for each selection made. The results of the query are returned in plain text. The formatting of this text is dependent on the particular WMS server used.

Seleção do formato

Se múltiplos formatos são suportados pelo servidor, uma caixa de combinação com os formatos suportados é automaticamente adicionado aos resultados da janela de identificação e o formato selecionado irá armazenar no projeto para a camada.

Suporte do formato GML

The identify Identify tool supports WMS server response (GetFeatureInfo) in GML format (it is called Feature in the QGIS GUI in this context). If “Feature” format is supported by the server and selected, results of the Identify tool are vector features, as from a regular vector layer. When a single feature is selected in the tree, it is highlighted in the map and it can be copied to the clipboard and pasted to another vector layer. See the example setup of the UMN Mapserver below to support GetFeatureInfo in GML format.

# in layer METADATA add which fields should be included and define geometry (example):

"gml_include_items"   "all"
"ows_geometries"      "mygeom"
"ows_mygeom_type"     "polygon"

# Then there are two possibilities/formats available, see a) and b):

# a) basic (output is generated by Mapserver and does not contain XSD)
# in WEB METADATA define formats (example):
"wms_getfeatureinfo_formatlist" "application/vnd.ogc.gml,text/html"

# b) using OGR (output is generated by OGR, it is sent as multipart and contains XSD)
# in MAP define OUTPUTFORMAT (example):
OUTPUTFORMAT
    NAME "OGRGML"
    MIMETYPE "ogr/gml"
    DRIVER "OGR/GML"
    FORMATOPTION "FORM=multipart"
END

# in WEB METADATA define formats (example):
"wms_getfeatureinfo_formatlist" "OGRGML,text/html"

22.1.7. Viewing Properties

Once you have added a WMS server, you can view its properties by right-clicking on it in the legend and selecting Properties. The WMS/WMTS layer properties is much like the raster layer properties so you will find detailed description at Caixa de Diálogo de Propriedades do Raster. However, there are some differences, which will be explained below.

22.1.7.1. Information properties

Separador de Metadados

O separador Metadados exibem a riqueza de informação sobre o servidor WMS, geralmente recolhidos a partir da declaração de de Capacidades devolvidos a partir desse servidor. Muitas das definições podem ser removidas através da leitura dos padrões WMS (veja OPEN-GEOSPATIAL-CONSORTIUM Referências Bibliográficas e Web), mas aqui estão algumas definições úteis:

  • Propriedades do Servidor

    • Versão do WMS — Versão do WMS suportada pelo servidor.

    • Image Formats — The list of MIME-types the server can respond with when drawing the map. QGIS supports whatever formats the underlying Qt libraries were built with, which is typically at least image/png and image/jpeg.

    • Identity Formats — The list of MIME-types the server can respond with when you use the Identify tool. Currently, QGIS supports the text-plain type.

  • Propriedades da Camada

    • Selecionado — Querendo ou não esta camada selecionado quando o seu servidor foi adicionado a este projeto.

    • Visível — Se esta camada é ou não selecionada como visível na legenda (ainda não usada nesta versão do QGIS).

    • Pode Identificar — Camada que retorna ou não resultados através do uso da ferramenta Identificar.

    • Pode ser transparente* — Se esta camada pode ou não ser renderizada com transparência. Esta versão do QGIS utilizará sempre a transparência se esta for “Sim” e a codificação da imagem suportar a transparência.

    • Can Zoom In — Whether or not this layer can be zoomed in by the server. This version of QGIS assumes all WMS layers have this set to Yes. Deficient layers may be rendered strangely.

    • Contagem em cascata — Os servidores WMS pode funcionar como proxy para outros servidores WMS para obter dados raster para uma camada. Esta entrada mostra quantas vezes o pedido para esta camada é avançada por peer nos servidores WMS para o resultado.

    • Fixed Width, Fixed Height — Whether or not this layer has fixed source pixel dimensions. This version of QGIS assumes all WMS layers have this set to nothing. Deficient layers may be rendered strangely.

    • WGS 84 Bounding Box — The bounding box of the layer, in WGS 84 coordinates. Some WMS servers do not set this correctly (e.g., UTM coordinates are used instead). If this is the case, then the initial view of this layer may be rendered with a very ‘zoomed-out’ appearance by QGIS. The WMS webmaster should be informed of this error, which they may know as the WMS XML elements LatLonBoundingBox, EX_GeographicBoundingBox or the CRS:84 BoundingBox.

    • SRC disponíveis — As projeções desta camada podem ser renderizadas pelo servidor WMS. Os mesmos estão listados num formato nativo WMS.

    • Disponível em estilo — Os estilos da imagem desta camada podem ser renderizadas pelo o servidor WMS.

22.1.7.2. Temporal properties

Raster temporal properties (namely Dynamic Temporal Control) can be set for WMS and WMTS layers. By default, when a time-dimension enabled WMS or WMTS layer is added to the project, it is indicated in the Layers panel with the indicatorTemporal Temporal Layer icon next to it. Its Temporal properties default to the Automatic temporal mode, meaning that the layer will follow the temporal controller’s current time range by default.

You can then opt to show a specific static time value for the layer by unchecking Dynamic Temporal Control and picking an option under Static WMS-T Temporal Range:

  • Server default

  • Predefined date with a server exposing data for non-contiguous temporal ranges or Predefined range with a server exposing a range of available dates. A Start date and End date are necessary in the latter case. Their expected formatting can be deduced from the reference time option (see below). depending on whether the provider has data for contiguous period or not

  • Follow project’s temporal range as defined in the project’s properties dialog

../../../_images/temporal_properties.png

Fig. 22.4 Temporal properties of a WMTS layer

Whatever temporal data control is in use, there are some WMS-T Settings to help display the correct temporal data:

  • Time slice mode which can be:

    • Use whole temporal range

    • Match to start of range

    • Match to end of range

    • Closest match to start of range

    • Closest match to end of range

  • Ignore time components (use dates only): If checked, the time component of temporal queries will be discarded and only the date component will be used in server requests.

You can also checkbox Use Specific WMS-T Reference Time picked from times reported in the layer’s capabilities. Convenient for servers which expose a non-contiguous set of date time instances (instead of a range of dates).

22.1.7.3. QGIS Server properties

In addition to the raster layer properties, publishing a WMS/WMTS layer with QGIS Server will display following options:

  • WMS Print layer: Allows to set alternative WMS layer that should be used for printing (in the GetProjectSettings reply). Convenient for WMTS layers that are generally not suitable for printing.

  • checkbox Publish WMS/WMTS data source uri: Allows a web client to fetch the WMS/WMTS data directly

  • checkbox Advertise as background layer

../../../_images/server_properties.png

Fig. 22.5 QGIS Server properties of a WMS/WMTS layer

22.1.8. Mostrar gráfico de legendas WMS no índice e layout

The QGIS WMS data provider is able to display a legend graphic in the table of contents’ layer list and in the print layout. The WMS legend will be shown only if the WMS server has GetLegendGraphic capability and the layer has getCapability url specified, so you additionally have to select a styling for the layer.

Se uma legendGraphic está disponível, será mostrada abaixo da camada. É pequena, e você tem que clicar sobre ela para abrir na dimensão real (devido à limitação arquitetônica QgsLegendInterface). Clicando sobre a legenda da camada abrirá um quadro com a legenda em resolução máxima.

In the print layout, the legend will be integrated at it’s original (downloaded) dimension. Resolution of the legend graphic can be set in the item properties under Legend ► WMS LegendGraphic to match your printing requirements.

A legenda irá exibir informações contextuais com base em sua escala atual. A legenda WMS será exibida somente se o servidor WMS tiver capacidade GetLegendGraphic e a camada getCapability url for especificada, então você tem que selecionar um estilo.

22.2. WCS Cliente

wcs O Serviço Web de Cobertura (WCS) fornecem acesso aos dados matriciais de forma a serem úteis à renderização cliente, como entrada a modelos científicos, e para outros clientes. O WCS pode ser comprado ao WFS e ao WMS. Como as instâncias WMS e WFS, o WCS permite aos clientes escolher porções de informação salvadas de servidores baseados condicionantes espaciais e outros critérios de consulta.

QGIS has a native WCS provider and supports both version 1.0 and 1.1 (which are significantly different), but currently it prefers 1.0, because 1.1 has many issues (i.e., each server implements it in a different way with various particularities).

The native WCS provider handles all network requests and uses all standard QGIS network settings (especially proxy). It is also possible to select cache mode (‘always cache’, ‘prefer cache’, ‘prefer network’, ‘always network’), and the provider also supports selection of time position, if temporal domain is offered by the server.

Aviso

Entering username and password in the Authentication tab will keep unprotected credentials in the connection configuration. Those credentials will be visible if, for instance, you shared the project file with someone. Therefore, it’s advisable to save your credentials in a Authentication configuration instead (configurations tab). See Sistema de Autenticação for more details.

22.3. WFS e WFS-T Cliente

In QGIS, a WFS layer behaves pretty much like any other vector layer. You can identify and select features, and view the attribute table. QGIS supports WFS 1.0.0, 1.1.0, 2.0 and OGC API - Features (OAPIF), including editing (through WFS-T). QGIS also supports background download and progressive rendering, on-disk caching of downloaded features and version autodetection.

In general, adding a WFS layer is very similar to the procedure used with WMS. There are no default servers defined, so you have to add your own. You can find WFS servers by using the MetaSearch plugin or your favourite web search engine. There are a number of lists with public URLs, some of them maintained and some not.

Carregando uma camada WFS

As an example, we use the Gateway Geomatics WFS server and display a layer.

https://demo.gatewaygeomatics.com/cgi-bin/wfs_gateway?REQUEST=GetCapabilities&VERSION=1.0.0&SERVICE=WFS

Para poder carregar uma camada WFS, primeiro crie uma conexão com o servidor WFS:

  1. Open the Data Source Manager dialog by pressing the dataSourceManager Open Data Source Manager button

  2. Habilitar a addWfsLayer :guilabel: aba WFS/OGC API-Features

  3. Clique em Novo… para abrir o diálogo Criar uma nova conexão WFS

  4. Insira Geomática do portal como nome

  5. Insira a URL (veja acima)

    ../../../_images/add_connection_wfs.png

    Fig. 22.6 Criando uma conexão com um servidor WFS

    Nota

    In case of an OGC API - Features (OAPIF), the URL to provide should be the landing page, ie the main page from which it is possible to navigate to all the available service endpoints.

  6. No diálogo de configuração WFS, você pode:

    • Indique a versão WFS do servidor. Se desconhecido, pressione o botão Detectar para recuperá-la automaticamente.

    • Define the maximum number of features retrieved in a single GetFetFeature request. If empty, no limit is set.

    • And depending on the WFS version, indicate whether to:

      • Enable feature paging and specify the maximum number of features to retrieve with Page size. If no limit is defined, then the server default is applied.

      • Forçar a Ignorar orientação dos eixos (WFS 1.1/WFS 2.0)

      • Inverter orientação do eixo

      • Use GML2 encoding for transactions.

    Aviso

    Entering username and password in the Authentication tab will keep unprotected credentials in the connection configuration. Those credentials will be visible if, for instance, you shared the project file with someone. Therefore, it’s advisable to save your credentials in an Authentication configuration instead (Configurations tab). See Sistema de Autenticação for more details.

  7. Pressione OK para criar a conexão.

Repare que as configurações proxy que definiu nas suas preferências são também reconhecidas.

Agora estamos prontos para carregar as camadas WFS a partir da conexão acima.

  1. Choose ‘Gateway Geomatics’ from the Server Connections drop-down list.

  2. Clique :guilabel:`Conectar’.

  3. Selecione a camada Parques na lista

  4. Você também pode escolher se deseja:

    • unchecked Usar título para nome da camada, mostrando o título da camada como definido no servidor no painel Camadass em vez de seu Nome.

    • checkbox Only request features overlapping the view extent

    • Change… the layer’s CRS to any other supported by the service

    • or build a query to specify particular features to retrieve from the service: double-click on the row of the layer to open the SQL Query Composer dialog. That dialog provides widgets to write an advanced SQL query relying on available tables and columns of the service, with sorting and filtering and a bunch of SQL functions, spatial predicates and operators.

      The query you build will appear after validation in the SQL column within the WFS / OGC API - Features table, and the filtered layer will display the Filtro indicador icon next to it in the Layers panel. It is thus possibe to adjust the query at any moment.

  5. Clique Adicionar para adicionar a camada ao mapa.

../../../_images/connection_wfs.png

Fig. 22.7 Adicionando uma camada WFS

O progresso do download é visualizado na parte inferior esquerda da janela principal do QGIS. Uma vez carregada a camada, você pode identificar e selecionar algumas feições e visualizar a tabela de atributos.