Page 1 of 1 (4 posts)

  • talks about »
  • tutorial

Tags

Last update:
Mon Mar 2 17:05:09 2015

A Django site.

QGIS Planet

Coordenadas dos cantos do mapa em QGIS | Map corner coordinates in QGIS

O desafio | The challenge

Em tempos na lista de discussão do qgis-pt alguém perguntou como dispor as coordenadas dos cantos do mapa no QGIS. Não estando (ainda) disponível tal funcionalidade, tentei chegar sem sucesso a uma solução que fosse de certa forma automática. Depois de remoer a ideia, e de ler um artigo do Nathan Woodrow, achei que a solução poderia passar por criar uma função para o construtor de expressões que pudesse ser usada em etiquetas no mapa.

Some time ago in qgis-pt mailing list, someone asked how to show the coordinates of a map corners using QGIS. Since this features wasn’t available (yet), I have tried to reach a automatic solution, but without success,  After some though about it and after reading a blog post by Nathan Woodrow, it came to me that the solution could be creating a user defined function for the expression builder to be used in labels in the map.

 A solução | The solution

Seguindo as indicações do referido artigo, comecei por criar um ficheiro userfunctions.py, que gravei na pasta .qgis2/python e, com uma ajuda do Nyall Dawson, escrevi o seguinte código.

Closelly following the blog post instructions, I have created a file called userfunctions.py in the  .qgis2/python folder and, with a help from Nyall Dawson I wrote the following code.

from qgis.utils import qgsfunction, iface
from qgis.core import QGis

@qgsfunction(2,"python")
def map_x_min(values, feature, parent):
 """
 Returns the minimum x coordinate of a map from
 a specific composer.
 """
 composer_title = values[0]
 map_id = values[1]
 composers = iface.activeComposers()
 for composer_view in composers():
  composer_window = composer_view.composerWindow()
  window_title = composer_window.windowTitle()
  if window_title == composer_title:
   composition = composer_view.composition()
   map = composition.getComposerMapById(map_id)
   if map:
    extent = map.currentMapExtent()
    break
 result = extent.xMinimum()
 return result

Depois de correr o comando import userfunctions na consola python (Módulos > Consola python), já conseguia usar a função map_x_min() (disponível na categoria python) numa expressão para obter o valor mínimo em X.

After running the command import userfunctions in the python console  (Plugins > Python Console), it was already possible to use the  map_x_min() function (from the python category) in an expression to get the minimum X value of the map.

Screenshot from 2014-09-09 16^%29^%29
Bastava então criar as restantes funções map_x_max(), map_y_min() e map_y_max(). Como parte do código seria repetida, decidi encapsulá-lo na função map_bound() que recebesse como argumentos o título do compositor de impressão e o id do mapa e me devolvesse a extensão do mesmo (sob a forma de um QgsRectangle).

All I needed now was to create the other three functions,  map_x_max(), map_y_min() and map_y_max().  Since part of code would be repeated, I have decided to put it in a function called map_bound(), that would use the print composer title and map id as arguments, and return the map extent (in the form of a QgsRectangle).

from qgis.utils import qgsfunction, iface
from qgis.core import QGis

def map_bounds(composer_title, map_id):
 """
 Returns a rectangle with the bounds of a map
 from a specific composer
 """
 composers = iface.activeComposers()
 for composer_view in composers:
  composer_window = composer_view.composerWindow()
  window_title = composer_window.windowTitle()
  if window_title == composer_title:
   composition = composer_view.composition()
   map = composition.getComposerMapById(map_id)
   if map:
    extent = map.currentMapExtent()
    break
 else:
  extent = None

 return extent

Com essa função disponível podia usá-la internamente nas funções para devolver cada um dos mínimos e máximos em X e Y, tornando o código mais compacto e fácil de manter. Adicionei ainda ao código original alguns mecanismos para evitar erros.

With this function available, I could now use it in the other functions to obtain the map X and Y minimum and maximum values, making the code more clear and easy to maintain. I also add some mechanisms to the original code to prevent errors.

@qgsfunction(2,"python")
def map_x_min(values, feature, parent):
 """
 Returns the minimum x coordinate of a map from a specific composer.
 Calculations are in the Spatial Reference System of the project.<br>
 <h2>Syntax</h2>
 <p>map_x_min(composer_title, map_id)</p>
 <h2>Arguments</h2>
 <p>composer_title - is string. The title of the composer where the map is.<br>
 map_id - integer. The id of the map.</p>
 <h2>Example</h2>
 <p>map_x_min('my pretty map', 0) -> -12345.679</p>
 """
 composer_title = values[0]
 map_id = values[1]
 map_extent = map_bounds(composer_title, map_id)
 if map_extent:
  result = map_extent.xMinimum()
 else:
  result = None

 return result

@qgsfunction(2,"python")
def map_x_max(values, feature, parent):
 """
 Returns the maximum x coordinate of a map from a specific composer.
 Calculations are in the Spatial Reference System of the project.<br>
 <h2>Syntax</h2>
 <p>map_x_max(composer_title, map_id)</p>
 <h2>Arguments</h2>
 <p>composer_title - is string. The title of the composer where the map is.<br>
 map_id - integer. The id of the map.</p>
 <h2>Example</h2>
 <p>map_x_max('my pretty map', 0) -> 12345.679</p>
 """
 composer_title = values[0]
 map_id = values[1]
 map_extent = map_bounds(composer_title, map_id)
 if map_extent:
  result = map_extent.xMaximum()
 else:
  result = None

 return result

@qgsfunction(2,"python")
def map_y_min(values, feature, parent):
 """
 Returns the minimum y coordinate of a map from a specific composer.
 Calculations are in the Spatial Reference System of the project.<br>
 <h2>Syntax</h2>
 <p>map_y_min(composer_title, map_id)</p>
 <h2>Arguments</h2>
 <p>composer_title - is string. The title of the composer where the map is.<br>
 map_id - integer. The id of the map.</p>
 <h2>Example</h2>
 <p>map_y_min('my pretty map', 0) -> -12345.679</p>
 """
 composer_title = values[0]
 map_id = values[1]
 map_extent = map_bounds(composer_title, map_id)
 if map_extent:
  result = map_extent.yMinimum()
 else:
  result = None

 return result

@qgsfunction(2,"python")
def map_y_max(values, feature, parent):
 """
 Returns the maximum y coordinate of a map from a specific composer.
 Calculations are in the Spatial Reference System of the project.<br>
 <h2>Syntax</h2>
 <p>map_y_max(composer_title, map_id)</p>
 <h2>Arguments</h2>
 <p>composer_title - is string. The title of the composer where the map is.<br>
 map_id - integer. The id of the map.</p>
 <h2>Example</h2>
 <p>map_y_max('my pretty map', 0) -> 12345.679</p>
 """
 composer_title = values[0]
 map_id = values[1]
 map_extent = map_bounds(composer_title, map_id)
 if map_extent:
  result = map_extent.yMaximum()
 else:
  result = None

 return result

As funções ficaram disponíveis no construtor de expressões na categoria “Python” (podia ter-lhe dado outro nome qualquer) e as descrições das funções são transformadas em textos de ajuda para fornecer ao utilizador informação de como utilizar as funções.

The functions became available to the expression builder in the “Python” category (could have been any other name) and the functions descriptions are formatted as help texts to provide the user all the information needed to use them.

Screenshot from 2014-09-09 15^%39^%19

Usando as funções recentemente criadas, foi fácil posicionar etiquetas  junto dos cantos do mapa com as coordenadas dos mesmos. Qualquer alteração à extensão do mapa, reflecte-se nas etiquetas, podendo por isso ser usadas convenientemente com a funcionalidade de atlas.

Using the created functions, it was now easy to put the corner coordinates in labels near the map corners. Any change to the map extents is reflected in the label, therefore quite useful to use with the atlas mode.

Screenshot from 2014-09-09 15^%40^%27

O resultado destas funções pode ser usado com outras. Na imagem seguinte apresenta-se uma expressão para apresentar as coordenadas de forma mais compacta.

The functions result can be used with other functions. In the following image there is a expression to show the coordinates in a more compact way.

Screenshot from 2014-09-09 15^%43^%55

Havia um senão… Para as funções ficarem disponíveis, seria necessário importá-las manualmente em cada utilização do QGIS. Algo que não era prático. Novamente com a ajuda do Nathan, fiquei a saber que podemos importar módulos Python no arranque do QGIS colocando na pasta .qgis2/python um ficheiro com o nome startup.py com os comandos de importação. Para o meu caso bastou o seguinte.

There was a setback… For the functions to become available, it was necessary to manually import them in each QGIS session. Not very practical. Again with Nathan’s help, I found out that it’s possible to import python modules at QGIS startup by putting a startup.py file with the import statements in the .qgis2/python folder. In my case this was enough.

import userfunctions

Conclusões | Conclusions

Fiquei bastante satisfeito com o resultado. A possibilidade do utilizador criar as usas próprias funções para usar em expressões vem mais uma vez demonstrar como é fácil personalizar e criar as minhas próprias ferramentas para QGIS. Já estou a matutar em mais aplicações para estar fantástica funcionalidade.

I was pretty satisfied with the end result. The ability to create your own functions in expressions demonstrates once more how easy it is to customize QGIS and create your own tools. I’m already thinking in more applications for this amazing functionality.

UT 9 - Qta da Peninha - Vegetação potencial

Os ficheiros Python com as funções criadas podem ser descarregados AQUI. Basta descompactar os dois ficheiros para a pasta .qgis2/python e reiniciar o QGIS, e as funções devem ficar disponíveis.

You can download the Python files with the functions HERE. Just unzip both files to the .qgis2/python folder, and restart QGIS, and the functions should become available.

Disclaimer: I’m not an English native speaker, therefor I apologize for any errors, and I will thanks any advice on how to improve the text.


Profile Tool tutorial

Profile Tool is a plugin for QGIS which makes it possible to generate (elevation) profiles for line features. The plugin is available through the default QGIS plugin repository. While testing the plugin, I found some aspects of using the tool might require additional instructions.

After installing and enabling the plugin, you will find the “Terrain profile” button in the plugin toolbar:

qgisprofiletool

The basic use case is as follows:

  1. Load the elevation raster and select this raster layer in the layer list.
  2. Press the “Terrain profile” button. This opens the plugin panel which consists of a graph area on the left and a raster layer list on the right. The raster layer you had selected will be added to the raster layer list.
  3. If you have “Selection: Temporary polyline” enabled, you can now draw a line in the map area. Double-click left to end drawing the line. (If you are paying close attention, you might have noticed the instructions in the status bar.)
  4. After you have finished drawing the line, the graph area will update and display the profile.

qgisprofiletool2

If you want to add another raster layer to the plugin, you need to first select the raster layer in the QGIS layer list and then press the “Add Layer” button in the Profile Tool panel.

To generate the profile for an existing line feature, you need to change the selection mode from “Temporary polyline” to “Selected polyline”. Then you need to select the vector layer which contains the line feature you want to use in the QGIS layer list. Finally, you can click on the line feature in the map area to select it. (Note that this selection is independent of any selections you might have going on using the default QGIS feature selection tools.)

If you change from the Profile Tool to any other tool such as “Pan Map” or “Identify”, you have to click the “Terrain profile” button again to re-enable drawing/selection a line for the Profile Tool.

Due to a bug, it is currently not possible to export the profile graph. An alternative is to open the “Table” tab of the Profile Tool panel which provides access to the profile data and copy the data into your preferred graphing application such as Calc or Excel.

If you want to see the Profile Tool in action, I recommend watching the introduction video by Lene Fischer (University of Copenhagen).


Group Stats Tutorial

Group Stats is a plugin for QGIS which makes it easy to calculate statistics for feature groups in a vector layer. Note that the plugin is still marked “experimental” so you have to allow experimental plugins in order to install it. I tried this plugin for the first time today and decided to write this post because it didn’t seem immediately obvious how to use it.

The plugin button is added to the vector toolbar and of course you can access it via vector menu.

groupstatsicon

The example I want to show is: How to calculate the total area of of each Corine Land Cover (CLC) class per state.

corineAT

After adding state information to the CLC datasets by intersecting CLC and state geometries from Natural Earth we can get started with Group Stats.

groupstats

The big area on the left will display the results. The input fields are on the right. The general idea is to drag and drop fields and/or functions into the “columns”, “rows” and “values” sections. (Double-clicking field names does not do anything.) To remove fields again, you have to drop them back into the field list.

To calculate the total area of of each Corine Land Cover (CLC) class per state, I chose land cover classes as columns, state names as rows and sum of areas as values:

groupstatsclc

It’s also possible to add multiple functions in the columns/rows input sections to calculate different statistics at once:

groupstats_functions

Group Stats can be used in many cases that otherwise require a Spreadsheet software. The results can be exported to CSV easily. Usability could certainly be improved by allowing common interactions such as removing fields by pressing the delete key or adding fields by double-clicking.


QGIS Video Tutorials

QGIS wiki now has it’s own section listing QGIS video tutorials.
If you know of any tutorials not listed yet, leave a comment and I’ll add them.

Together with the newly started “How to I do that in QGIS” tutorial collection, this will hopefully become the number one reference for both new users doing their first GIS-related work and advanced uses interested in the latest QGIS features.


  • Page 1 of 1 ( 4 posts )
  • tutorial

Back to Top

Sponsors