Page 1 of 2 (34 posts)

  • talks about »
  • uncategorized

Tags

Last update:
Thu Sep 3 22:40:10 2015

A Django site.

QGIS Planet

Registration open for QGIS hackfest in Gran Canaria, November 2015

Dear QGIS developers

Collage Las Palmas de Gran Canaria

We will be holding our 14th hackfest in Gran Canaria over November 5th – November 8th, 2015. You can read more about the plans for this meet up and register your intention to attend on the hackfest wikipage. This is a developer centric hackfest where we invite coders, documenters, testers, graphic artists, translators and anyone else who is interested in improving QGIS for the benefit of all our users. General users of QGIS are of course also welcome to join us, but we will not be holding any specific user-centric workshops or talks like we do at our user conferences.

The QGIS hackfests are an important aspect of the project, playing an key role in facilitating collaboration and planning within the community of developers and contributors who combine their efforts to put out three releases of QGIS each year. We rely on the goodwill and sponsorship of our grateful users and their host organisations to financially sustain the QGIS project. If you are in a position of influence, we ask you to please consider sponsoring QGIS to support this hackfest and other project related activities.

We would like to thank Pablo Fernández Moniz and his co-organisers from Universidad de las Palmas de Gran Canaria for organising the event. If you are able to support his event organisation activities in any way, please contact him at 

We look forward to seeing your all there!

The QGIS Team


Call for applications: QGIS API Documentation Improvement

Dear QGIS DevelopersIn the last few years we have been steadily improving the amount of funding we are able to accumulate in the QGIS project. Our goal in obtaining funding is always to ‘make QGIS better’. Up until now we have focussed funding on high profile aspects of the project: Funding regular hackfests, paying for bug fixing work prior to releases, funding infrastructure such as servers, domain name registrations etc.

With improved funding levels we now have the opportunity to also start addressing some of the many less obvious components of QGIS that badly need attention, but often don’t attract volunteers. In our July 2015 PSC meeting it was agreed that we would start this initiative by funding one or more developers to improve the python documentation in QGIS. Here, briefly, is the vision:

Lets take our inspiration from Qt. As a foundational library for QGIS, I have always loved the fact that Qt4 is so well documented. Take a look at this for example – http://doc.qt.io/qt-4.8/qlabel.html#details

The Qt4 documentation provides a readable narrative explaining the purpose (with images and illustrations if needed) of each class. It also provides a code snippet, which in many cases you can simply cut and paste into your code and then tweak to get started.

As a PyQGIS programmer you have two main resources: The QGIS Python cookbook and the QGIS C++ API documentation. The cookbook is an excellent resource, but it is hard to keep it synchronised with the code base – so examples often run the risk of being out of date, or don’t leverage new functionality that makes its way into the code base. The C++ documentation is good in terms of coverage, but it often lacks detail and as a python programmer you may find it a bit off putting since the text is littered with examples using pointers. Also, the C++ documentation isn’t always a one to one match for python users, and doesn’t explain python specific behaviour such as how ownership is passed around with returning objects.

Wouldn’t it be nice if the C++ API documentation also included the content that is in the python cookbook? And wouldn’t it be nice if the C++ documentation became the C++ *and* Python API documentation – catering for users of both programming languages and providing for a single point of reference and maintenance? Even better the python documentation would live right in the C++ code, so that anytime someone touches the code base they can easily maintain the documentation without needing to jump through a lot of hoops.

For this funded effort we are thus seeking one or more individuals to lay the foundation for this work:

  • establish norms and guidelines for improving the doxygen API docs so that each documented resource can include both python and C++ documentation.
  • port the cookbook content over to the API documentation
  • create doxygen pages to provide a starting point for python programmers to be able to carry out common activities they need
  • populate the API docs with Python examples and improved descriptions
  • do these in a nice clear and concise writing style, again taking inspiration from the fine work that Qt has done
  • perhaps do something really smart to generate docs from the SIP API and incorporate it into our doxygen doctree?

If you think this is something you are able to do, please contact the QGIS PSC using this form and let us know!

Click here to apply here if you are interested in this work


Point release QGIS 2.8.3 ‘Wien’ is ready!

We are very pleased to announce the point release of QGIS 2.8.3 ‘Wien’. Wien is German for ‘Vienna’ – host city to our developer meet up in November 2009 and again in March 2014.

As point release it contains no new features, but 150 changes to fix bugs (see https://github.com/qgis/QGIS/compare/final-2_8_2…final-2_8_3 for a full list).

Even when only fixes are added to software they introduce the possibility of new bugs – if you encounter any problems with this release, please file a ticket on the QGIS Bug Tracker (http://hub.qgis.org/). Please consult the existing and closed issues there before filing any new ones.

The source code and binaries for Windows, Debian and Ubuntu are already available via the large download link on our home page (http://qgis.org/). More packages will follow as soon as the package maintainers finish their work. Please revisit the page if your platform is not available yet.

Thanks

We would like to thank the developers, documenters, testers and all the many folks out there who volunteer their time and effort (or fund people to do so).

From the QGIS community we hope you enjoy this release! If you wish to donate time, money or otherwise get involved in making QGIS more awesome, please wander along to http://qgis.org and lend a hand!

Finally we would like to thank our official sponsors for the invaluable financial support they provide to this project:

Gold Sponsor:
Asia Air Survey, Japan (http://www.asiaairsurvey.com/)

Silver Sponsors:
Sourcepole AG, Switzerland (http://www.sourcepole.com/)
Office of Public Works, Ireland, Ireland (http://www.opw.ie/)
AGH University of Science and Technology, Poland (http://www.agh.edu.pl/en)
State of Vorarlberg, Austria (http://www.vorarlberg.at/)

Bronze Sponsors:
Nicholas Pearson Associates, UK (http://www.npaconsult.co.uk/)
QGIS Poland, Poland (http://qgis-polska.org/)
http://www.terrelogiche.com, Italy (http://www.terrelogiche.com)>
http://www.geosynergy.com.au, Australia (http://www.geosynergy.com.au/)
Gaia3D, Inc., South Korea (http://www.gaia3d.com/)
Royal Borough of Windsor and Maidenhead, UK (http://www.rbwm.gov.uk/)
Chartwell Consultants Ltd., Canada (http://www.chartwell-consultants.com/)
Trage Wegen vzw, Belgium (http://www.tragewegen.be/)
GFI – Gesellschaft für Informationstechnologie mbH, Germany (http://www.gfi-gis.de/)
GKG Kassel,(Dr.-Ing. Claas Leiner), Germany (http://www.eschenlaub.de/)
GIS-Support, Poland (http://www.gis-support.com/)
ADLARES GmbH, Germany (http://www.adlares.com/)
http://www.molitec.it, Italy (http://www.molitec.it/)
http://www.argusoft.de, Germany (http://www.argusoft.de/)
Customer Analytics, USA (http://www.customeranalytics.com/)
Avioportolano Italia, Italy (http://www.avioportolano.it/)
Faculty of Geology, Geophysics and Environmental Protection,
AGH University of Science and Technology, Poland (http://www.wggios.agh.edu.pl/en)
Urbsol, Australia (http://www.urbsol.com.au/)
MappingGIS, Spain (http://www.mappinggis.com/>)
GIS3W, Italy (http://www.gis3w.it/)
Lutra Consulting, UK (http://www.lutraconsulting.co.uk/)

A current list of donors who have made financial contributions large and small to the project can be seen on our donors list (http://qgis.org/en/site/about/sponsorship.html#list-of-donors).

If you would like to become and official project sponsor, please visit our sponsorship page for details. Sponsoring QGIS helps us to fund our six monthly developer meetings, maintain project infrastructure and fund bug fixing efforts (http://qgis.org/en/site/about/sponsorship.html#sponsorship).

QGIS is Free software and you are under no obligation to pay anything to use it – in fact we want to encourage people far and wide to use it regardless of what your financial or social status is – we believe empowering people with spatial decision making tools will result in a better society for all of humanity.

Sponsoring QGIS helps us to fund our six monthly developer meetings, maintain project infrastructure and fund bug fixing efforts.

Happy QGISing!

Regards,

The QGIS Team!


Postgres Expression Compiler

Performance This project is all about performance of QGIS with a postgres/postgis database. A lot of people have QGIS connected to postgres/postgis (if you don’t: it’s a great combination in the open source geo stack). Databases are really optimized for

QGIS 2.10 ‘Pisa’ released!

We are very pleased to announce the release of QGIS 2.10 ‘Pisa’. Pisa was the host city to our developer meet up in March 2010.

Latest Release

This is another release following our four monthly schedule.  It again brings many nice new features to QGIS.  With the release of 2.10 the previous release 2.8 ‘Wien’, which is designated a long term release (LTR) is moved to the long term package repositories and is the first to arrive there.  If you are working in a production environment where you wish to be more conservative about rolling out new features to your users, you will probably prefer those. Of course going with the feature frozen LTR also means that you’ll have to learn
to do without all the nice new things introduced in 2.10 and above until the next long term is released next year.

New Features in QGIS 2.10 ‘Pisa’

QGIS 2.10 includes many great new features, tweaks and enhancements to make the most popular Free desktop GIS even more feature filled and useful.  Visit the visual changelog that highlights some of the new additions (http://qgis.org/en/site/forusers/visualchangelog210/index.html).

Whenever new features are added to software they introduce the possibility of new bugs – if you encounter any problems with this release, please file a ticket on the QGIS Bug Tracker (http://hub.qgis.org).

The source code and binaries for Windows, Debian and Ubuntu are already available via the large download link on our home page: http://qgis.org.  More packages will follow as soon as the package maintainers finish their work. Please revisit the page if your platform is not available yet.

Thanks

We would like to thank the developers, documenters, testers and all the many folks out there who volunteer their time and effort (or fund people to do so).

From the QGIS community we hope you enjoy this release! If you wish to donate time, money or otherwise get involved in making QGIS more awesome, please wander along to qgis.org and lend a hand!

Finally we would like to thank our official sponsors for the invaluable financial support they provide to this project:

GOLD Sponsor: Asia Air Survey, Japan
SILVER Sponsor: Sourcepole AG, Switzerland
SILVER Sponsor: State of Vorarlberg, Austria
SILVER Sponsor: Office of Public Works, Ireland, Ireland
BRONZE Sponsor: GeoSynergy, Australia
BRONZE Sponsor: Gaia3D, South Korea
BRONZE Sponsor: Royal Borough of Windsor and Maidenhead, UK
BRONZE Sponsor: Chartwell Consultants Ltd, Canada
BRONZE Sponsor: Trage Wegen vzw, Belgium
BRONZE Sponsor: GFI – Gesellschaft für Informationstechnologie mbH, Germany
BRONZE Sponsor: GKG Kassel,(Dr.-Ing. Claas Leiner), Germany
BRONZE Sponsor: GIS-Support, Poland
BRONZE Sponsor: ADLARES GmbH, Germany
BRONZE Sponsor: www.molitec.it, Italy
BRONZE Sponsor: www.argusoft.de, Germany
BRONZE Sponsor: Customer Analytics, USA
BRONZE Sponsor: Avioportolano Italia, Italy
BRONZE Sponsor: Faculty of Geology, Geophysics and Environmental Protection, AGH, University of Science and Technology, Poland
BRONZE Sponsor: Urbsol, Australia
BRONZE Sponsor: MappingGIS, Spain
BRONZE Sponsor: GIS3W, Italy
BRONZE Sponsor: Lutra Consulting, UK
BRONZE Sponsor: www.openrunner.com, France

A current list of donors who have made financial contributions large and small to the project can be seen on our donors list. If you would like to become and official project sponsor, please visit our sponsorship page for details. Sponsoring QGIS helps us to fund our six monthly developer meetings, maintain project infrastructure and fund bug fixing efforts.

QGIS is Free software and you are under no obligation to pay anything to use it – in fact we want to encourage people far and wide to use it regardless of what your financial or social status is – we believe empowering people with spatial decision making tools will result in a better society for all of humanity.

Happy QGISing!

Regards,

The QGIS Team!


QGIS Quality and Testing

I promised that I will write a bit about what I’ve been up to at the last QGIS developer meeting – apart from the social part we also got some work done there. So let me start with something that

Ti piace avere QGIS ben tradotto in italiano? Ora puoi contribuire

Avere tutto QGIS, incluso il programma, i manuali e il sito web, tradotti in italiano è una bella comodità; questo richiede uno sforzo notevole, per cui il tuo aiuto è essenziale. Fai una donazione tramite: http://qgis.it/#translation

Importing CSV files into PostgreSQL using the DB Manager in QGIS

There is very useful tool in QGIS that can import very large CSV files into PostgreSQL rapidly and reliably. The DB Manager’s “Import Vector Layer” tool. Contrary to its highly misleading title it can import CSV files as well. Open the DB Manager (menu Database – DB Manager). Then select the database where you want to store your table and click the “Import layer/file” icon.

Icon_to_ClickFrom the Import Vector Layer GUI, locate our CSV file on disk and enter the name of your new table in the Table box and click OK. Yes, it’s that simple. Proceeding this, you may need to select an text encoding scheme, files created on Windows often use ISO-8859-1 (Latin-1) instead of UTF-8 encoding. In my case, I was able to import a large statistical data set describing the energy efficiency of 525,500 Irish homes (432 megabytes) into PostgreSQL in ~15 minutes. After the CSV file is imported, you can optionally add it to your project using the DB Manager, right-click the table and select Add to Canvas. Don’t use the “Add PostGIS Layers” menu, it’s not a PostGIS layer.

Import_GuiAnd one more useful tip. You can convert Tab delimited text to CSV using QGIS. Load a Tab delimited text file into QGIS using the Add Delimited Text Layer GUI, then right click the imported file in the layer panel and save it as a CSV file.


CartoDB wins best “high-growth web entrepreneur” at the 2014 European Web Entrepreneur of the Year Awards

CartoDB, the FOSS powered web mapping solution, was honoured at the 2014 European Web Entrepreneur of the Year Awards along with three other companies at Dublin’s Web Summit on November 7th. The awards, presented by a European Commission backed body, were announced after a six month competition that involved public voting across four categories. CartoDB won the award for best “high-growth web entrepreneur”. CartoDB now has a growth rate of over 15% per month and customers in over 30 countries.

In September, a partner company of CartoDB, Kudos Ltda., released a plug-in that allows QGIS users to view, create, edit and delete data stored on their CartoDB accounts. Here is a map I created with the help of the new CartoDB plug-in that shows mountains and hills across the contiguous United States in the form of a heat map.

CartoDB and QGIS illustrate the exciting convergence between web hosted and desktop GIS, where interactive maps created in QGIS can be quickly published on the web and viewed by a worldwide audience.

FinalCartoDB


The Coastal Vignette

Vignette2

Coastal Vignette seen on an old Irish ‘6-Inch map’

Occasionally on old maps you may see a pleasing decorative effect on bodies of water called a “Coastal Vignette”, these are fine lines that highlight coastlines and lake shores. The example seen above is from a ca. 100 year old “6-inch map” of Lough Nafooey in County Galway, Ireland. I presume the Coastal Vignette effect in this example was hand drawn, it required considerable skill and patience.

These is no plugin for creating Coastal Vignettes in QGIS just yet, so I developed a simple technique to recreate the effect using the raster Proximity (Raster Distance)’ algorithm accessible in the Processing Toolbox.

In order to use the Proximity Analysis tool I first converted a Shapefile polygon depicting the sea off Dublin into a 10 by 10 metre resolution Raster using the menu command ‘Raster – Conversion – Rasterize (Vector to raster)’.

Box

This generated a Raster that coded the Sea as ‘1’ (white) and ‘0’ (black) for Land.

Next, I selected ‘Proximity (raster distance)’  from the Processing Toolbox – (GDAL/OGR) – [GDAL] Analysis – Proximity (raster distance). You can quickly find the command by typing the algorithm’s name in the box above the Processing Toolbox.

Screenshot5

I entered 0 in the ‘Values’ box, this tells the Proximity algorithm to measure the distance away from land (a value of 0). The resulting Raster contains cell values that correspond to the distance away from the coast in metres, which I styled below.

The final step is to create Contours Lines from the Proximity analysis result using the menu item Raster – Contour. In my case I used an “interval between the contour lines” of 200 metres and I added an Attribute name called “DIST”.

Screenshot7

The resulting contour lines have distance attributes attached to them can be used to create a Graduated colour style if needed, though in my cause I manually edited the attributes of 10 contour lines nearest the coast and I gradually increased the transparency of the mid-grey contour lines from opaque at the coast to fully transparent out at sea. I made the remaining contour lines transparent.

And here is the finished result, with the Sea and an OpenStreetMap base map styled to look just like Google Maps.

Finished Vignette 2


Dica para ajustar posição de símbolos em QGIS | Hack to adjust map symbols location in QGIS

De quando em vez aparecem-me zonas com demasiado símbolos no mesmo local, e pensei como seria fantástico se os pudesse arrastar para um local mais conveniente sem ter de alterar as suas geometrias, tal como é possível fazer com as etiquetas. Esse pensamento deu-me a ideia base para a dica que vou demonstrar.

Now and then I get too many map symbols (points) in the same place, and I thought how nice it would be if we could drag n’ drop them around without messing with their geometries position, just like we do with labels. That thought gave me an idea for a cool hack.

Escolha a sua camada de pontos e comece por criar dois novos campos chamados symbX e symbY (Tipo: Decimal; Tamanho: 20; precisão: 5). No separador “Estilo” das propriedades da camada, defina para cada nível do seu símbolo o seguinte: Escolher “unidade do mapa” como a unidade para as opções de afastamento; Usar a seguinte expressão na opção afastamento das propriedades definidas por dados.

Choose your point layer and start by creating two new fields called symbX and symbY (Type: Decimal number; Size: 20; Precision: 5). Now go the layer properties and in the Style tab edit your symbol. For each level of your symbol select “map units” as the offset units, and set the following expression in the offset data define properties option:


CASE WHEN symbX IS NOT NULL AND symbY IS NOT NULL THEN
    tostring($x - symbX) + ',' + tostring($y - symbY)
ELSE
    '0,0'
END

Screenshot from 2015-02-22 18:18:43

Tenha atenção que, se as coordenadas do seu mapa tiver valores negativos, será necessário uma pequena alteração ao código. E. g., se tiver valores negativos em X deverá usar-se  antes a expressão “tostring(symbX -$x)”.

Beware that if your coordinates have negative values you need to adapt the code. E.g., If you have negative values in X you should use “tostring(symbX -$x)” instead.

De forma temporária coloque etiquetas na sua camada usando um texto pequeno (eu usei o ‘+’ (sinal de mais) centrado e com um buffer branco) e defina as coordenadas X e Y dos propriedades definidadas por dados usando os campos symbX e symbY,

Now, temporarly  label your layer with a small convenient text (I used a centered ‘+’ (plus sign) with a white buffer) and set its coordinates to data defined using the symbX and symbY Fields.

Screenshot from 2015-02-22 22:42:07

A partir desse momento, quando usar a ferramenta de mover etiquetas, não só alterará a posição da etiqueta, mas também a do próprio símbolo! Fantástico, não?

From this point on, when you use the move label tool, not only the label position change but also the actual symbol! Pretty cool, isn’t it?

anim

Note que as geometria dos elementos não são alteradas durante o processo. Para além disso, lembre-se que neste caso também poderá adicionar linhas de guia para ligar os símbolos à posição original do ponto.

Notice that the features geometries are not changed during the process. Also, remember that in this case you can also add leading lines to connect the symbols to the original position of the points.


Calcular coordenadas do centroide de polígonos | Calculate polygon centroid’s coordinates

Tive necessidade de, numa camada de polígonos, adicionar colunas à tabela de atributos com as coordenadas dos centroides das geometria. Cheguei às seguintes expressões para calcular as coordenadas X e Y, respectivamente:

I had the need to add columns with the coordinates of polygons centroids. I came up with the following expressions to calculate X e Y, respectively:

xmin(centroid($geometry))
ymin(centroid($geometry))

A expressão parece bastante banal, mas ainda demorei a perceber que, não existindo funções x(geometry) e y(geometry), podia usar as funções xmin() e ymin() para obter as coordenadas dos centroides dos polígonos. Uma vez que esta não foi a primeira vez que precisei de usar estas expressões, fica agora o registo para não me voltar a esquecer.

The expression seems quite simple, but it toke me some time before I realize that, not having a x(geometry) and y(geometry) functions, I could use the xmin() and ymin() to get the coordinates of the polygons centroids. Since this wasn’t the first time I had to use this expressions, this post will work as a reminder for the future.


Etiquetas com guias em QGIS e Postgis | Labels leading lines with QGIS and Postgis

Recentemente tive necessidade de colocar etiquetas de texto em elementos com geometrias muito próximas, fazendo com que as mesmas colidissem umas com as outras.

Recently I had the need to add labels to features with very close geometries, resulting in their collision.

Capturar_3

Controlando a posição das etiquetas através dos dados (para configurar rapidamente a camada usei o plugin “layer to labeled layer“) e usando a ferramenta do qgis para mover as etiquetas, foi relativamente fácil reposicioná-las de forma a que todas coubessem no mapa sem se sobreporem. Porém, em certos casos, tornou-se difícil perceber a que elemento cada uma correspondia.

Using data-defined override for label’s position (I have used layer to labeled layer plugin to set this really fast) and the QGIS tool to move labels, it was quite easy to relocate them to better places. However, in same cases, it was difficult to understand to which geometry they belonged.

Capturar_2

Precisava de criar “linhas de guia” que, sempre que necessário, ligassem o elemento e a respectiva etiqueta. Conhecia a existência de outro excelente plugin, chamado “Easy Custom Labeling” do Regis Haubourg, que fazia o que eu pretendia, mas como criava um duplicado da camada original significava que a mesma não seria actualizada quando a camada original fosse editada.

I needed some kind of leading lines to connect, whenever necessary, label and feature. I knew another great plugin called “Easy Custom Labeling“, by Regis Haubourg, that did what I needed, but it would create a memory duplicate of the original layer, wish meant that any edition on the original layer wouldn’t be updated in the labels.

Uma vez que os dados estavam guardados numa base de dados PostgreSQL/Postgis, decidi criar uma consulta que me devolvesse uma camada com as linhas de guia. Usei a seguinte consulta no gestor de bases de dados:

Since the data were stored in a PostgreSQL/Postgis database, I have decided to create a query that would return a layer with leading lines. I used the followind query in DB manager:

SELECT
  gid,
  label,
  ST_Makeline(St_setSRID(ST_PointOnSurface(geom),27493), St_setSRID(St_Point(x_label::numeric, y_label::numeric),27493))
FROM
  epvu.sgev
WHERE
  x_label IS NOT NULL AND
  y_label IS NOT NULL AND
  NOT ST_Within(ST_Makeline(St_setSRID(ST_PointOnSurface(geom),27493), St_setSRID(St_Point(x_label::numeric, y_label::numeric),27493)),geom))

Esta consulta cria uma linha composta pelo centro (interno) do polígono e a coordenada do ponto para a qual a etiqueta foi movida. A última condição da cláusula WHERE garante que a linha só é criada se a coordenada da etiqueta não estiver dentro do polígono.

This query create a line by using the feature centroid as starting point and the label coordinate as end point. The last condition on the WHERE statement assures that the lines are only created for labels outside the feature.

Capturar_1

Com a camada resultante carregada no meu projecto, basta-me mover as etiquetas e gravar a edição da camada original para que a respectiva linha de guia apareça.

With the resulting layer loaded in my project, all I need is to move my labels and save the edition (and press refresh) to show a nice leading line.

guidelines


Setting up a Fedora 21 QGIS Workstation

I have been a long time Ubuntu user (I have actually been using it since Ubuntu 4.10 ‘Warty Warthog’) – the first official release. The advent of Ubuntu saw an end to my distro hopping whilst looking for the ‘perfect linux distro’.

Recently though, Ubuntu has been losing momentum in my opinion – especially in terms of supporting the latest Gnome desktop editions and catering for those of us who like to use a leading edge platform for our developer workstations. I was particularly curious to see if QGIS runs nicely under Wayland, the next-generation graphics environment for Linux.

I have been using docker heavily for the last year and have come to the point where I feel that the underlying Linux flavour is less important since I can fairly arbitrarily deploy applications in docker containers using whichever flavour of Linux inside the container is most convenient.

Thus I decided to try and see how easy it would be to get Fedora 21 installed on my MacBook 13″ Laptop which was running Ubuntu quite nicely until now. In the Gist below, I detail the various installation steps I took to get my standard suite of applications installed. These include:

  • docker
  • QGIS compilation build chain
  • PyCharm 4
  • Shutter
  • Skype
  • QtCreator / QtDesigner etc.
  • btsync
  • Google Chrome
  • vlc and assorted video codecs
  • keepassx
  • Elegance gnome theme (must-have if you use Gnome!)

 

Workspace 1_130

I will keep the above Gist updated as I tweak my configuration, but by and large the migration to Fedora has been fairly painless and I am enjoying working on the latest Gnome desktop. I was able to replicate pretty much all of the application stack I ran on Ubuntu, though in some cases the setup & installation of applications was a little more complex than on Ubuntu, and in one case (btsync-gtk-gui) I have not yet found a binary installation package.

Séries de mapas com formatos múltiplos em QGIS 2.6 – Parte 2 | Multiple format map series using QGIS 2.6 – Part 2

No último artigo, tentei mostrar como usei o QGIS 2.6 para criar séries de mapas cuja orientação da folha se adaptasse à forma do elemento do atlas. Esse método é útil quando a escala final dos mapas não é relevante, ou quando os elementos usados no atlas têm uma dimensão muito semelhante, permitindo a adopção de uma escala única. No entanto, quando é necessário manter a mesma escala de impressão dos mapas e os elementos do atlas apresentam diferenças de extensão, é necessário alterar o tamanho da folha. Nesta segunda parte do artigo, tentarei mostrar como cheguei a uma solução para isso.

In my last post, I have tried to show how I used QGIS 2.6 to create a map series where the page’s orientation adapted to the shape of the atlas features. This method is useful when the final scale of the maps is irrelevant, or when the size of the atlas elements is  similar, allowing one to use a fixed scale. On the other hand, when using a fixed scale is mandatory and the features size are too different, it is needed to change the size of the paper. In this second part ot the post, I will try to show how I came to a solution for that.

Como base usei o mapa criado na 1ª parte do artigo, do qual fiz um duplicado. Para exemplificar o método procurei criar uma série de mapas à escala 1:2.000.000. Uma vez que iria adaptar tanto a altura como a largura da folha aos elementos do atlas, não me precisava de preocupar com a orientação da folha em si e por isso comecei por desactivar as propriedades definidas por dados na opção orientação.

As a base, I used the map created in the previous post, from which I did a duplicate. To exemplify the method I tried to create a map series at 1:2.000.000 scale. Since I was going to change both width and height of the paper, I did not need to set an orientation, and therefore I deactivated the data defined properties of the orientation option:

Fiz algumas contas usando a escala, as dimensões do elemento do atlas e as margens definidas anteriormente e e cheguei às seguintes expressões a usar na  largura e altura da folha, respectivamente:

With some maths with the map scale, the size of the atlas feature and the already defined margins, I came up with the following expressions to use, respectively,  in width and height:

((bounds_width( $atlasgeometry ) / 2000000.0) * 1000.0) * 1.1 + 10
((bounds_height( $atlasgeometry ) / 2000000.0) * 1000.0) * 1.1 + 30

Passo a explicar. (bounds_width( $atlasgeometry ) / 2000000.0) é a largura do elemento do atlas representado à escala 1:2.000.000 em unidades do projecto (neste caso metros). Este resultado é multiplicado por 1000 para o converter em milímetros (unidade usada nas definições do compositor). Para que o elemento de atlas não ficasse resvés aos limites do mapa decidi dar 10% de margem em torno do mesmo, o que justifica a multiplicação por 1.1. E por fim adicionei a dimensão das margens do mapa que tinham sido definidas na 1ª parte do artigo (i.e., 20 mm, 5 mm, 10 mm, 5 mm).

Allow me to clarify. (bounds_width( $atlasgeometry ) / 2000000.0) is the atlas feature’s width in meters when represented at 1:2.000.000. This is multiplied by 1000 to convert it to millimeters (the composer’s settings units). In order to keep the atlas feature not to close to the margin, I have decided to add 10% of margin around it, hence the multiplication by 1.1. To finish I add the map margins value,that where already set in the previous post (i.e.,20 mm, 5 mm, 10 mm, 5 mm)

Screenshot from 2014-11-16 22:58:34

Como se pode ver pela imagem anterior, após a introdução das expressões nas opções de largura e altura da folha, a sua dimensão já se alterava em função do tamanho do elemento de atlas. No entanto, como seria de esperar, os itens do mapa mantiveram-se teimosamente na mesma posição. Foi por isso necessário alterar as expressões definidas para a dimensão e posição de cada um deles.

As one can see from the previous image, after setting the expressions in the paper width and height options, it’s size already changed according to the size of the atlas features. But, as expected, all the itens stubbornly kept their positions.For that reason, it has been necessary to change the size and position expressions for each of then.

Começado pelo tamanho do item de mapa, as expressões a usar na altura e largura não foram difíceis de perceber uma vez que seriam as dimensões da folha menos as margens:

Starting by the map item size, the expressions to use in width and height were not difficult to understand since they would be the paper size without the margins size:

((bounds_width( $atlasgeometry ) / 2000000.0) * 1000.0) * 1.1
((bounds_height( $atlasgeometry ) / 2000000.0) * 1000.0) * 1.1

Screenshot from 2014-11-16 23:07:43

Para posicionar correctamente os elementos, bastou substituir nas expressões das opções X e Y os “CASE WHEN … THEN … END” que determinavam o tamanho da largura ou altura da folha, pelas expressões descritas anteriormente. Por exemplo, as expressões usadas para a posição da legenda em X e Y:

To position the items correctly, all was needed was to replace the “CASE WHEN … THEN … END” statement by the expressions defined before. For instance, the expressions used in the X and Y options for the legend position:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 297 ELSE 210 END) - 7
(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 210 ELSE 297 END) - 12

Passaram a ser, respectivamente:
Became, respectively:

(((bounds_width( $atlasgeometry ) / 2000000.0) * 1000.0) * 1.1 + 10) - 7
(((bounds_height( $atlasgeometry ) / 2000000.0) * 1000.0) * 1.1 + 30) - 12

Screenshot from 2014-11-16 23:22:40

Alterando as expressões de posicionamento X e Y dos restantes itens do compositor cheguei à estrutura final.

Changing the expressions of the X and Y position options for the remaining composer’s items I have reached the final layout.

alaska_region_Kenai Peninsula

Depois disso, a impressão/exportação de todos os (25) mapas ficou, mais uma vez, à distância de um só clique.

Once again, printing/exporting all (25) maps was only one click away.

mosaico_regioes_fixed

Uma vez que o QGIS permite exportar imagens do compositor georreferenciadas, adicionando-as ao QGIS obtive este resultado interessante.

Since QGIS allows exporting the composer as georeferenced images, opening all maps in QGIS I got this interesting result.

Screenshot from 2014-11-17 00:02:38

Como se pode ver pelos resultados, através deste método, podemos obter mapas com formatos bastante estranhos. Por essa razão, na 3ª e última parte deste artigo, procurarei mostrar como criar uma série de mapas com escala fixa, mas usando formatos de folhas standard (A4, A3, A2, A1 e A0).

As one can see by the results, using this method, we can get some quite strange formats. That is why in the 3rd and last post of this article, I will try to show how to create a fixed scale map series using standard paper formats (A4, A3, A2, A1 e A0).

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.


Dissolver polígonos em Postgres\Postgis

Trata-se de um cenário muito recorrente em análise espacial. Tendo uma camada\tabela composta por diversos polígonos, queremos “juntá-los” de acordo com valores distintos de um ou mais atributos (exemplo: de uma camada com os limites de freguesias, queremos obter os concelhos, ou, da COS ao 3º nível, obter o 2º ou o 1º)

Este artigo tem como objectivo mostrar como fazê-lo em Postgres\Postgis.

Tabela de exemplo

Como exemplo vou usar uma tabela como o seguinte formato:

CREATE TABLE tabela_1
    (gid serial PRIMARY KEY,
     campo1 character varying(128),
     campo2 integer,
     geom geometry(MultiPolygon,27493);

tabela1_original_tabela

tabela1_original

Dissolver todos os polígonos

Em primeiro lugar podemos simplesmente agregar todos os elementos num multi-polígono único. Para tal usamos a função ST_Union().

SELECT
    ST_Union(t.geom) as geom
FROM
    tabela_1 as t;

tabela1_union

Separar polígonos que não sejam contíguos

Se por outro lado não quisermos que o resultado apresente multi-polígonos usamos a função ST_Dump() recolhendo o campo da geometria.

SELECT
    (ST_Dump(ST_Union(t.geom))).geom as geom
FROM
    tabela_1 as t;

tabela1_union_dump

Dissolver polígonos com base em valores dos campos

Se quisermos dissolver os polígonos que tenham valores iguais num ou mais campos, basta incluí-los na cláusula GROUP BY. Se quisermos que esses campos apareçam no resultado (geralmente queremos) há que referi-los no início do SELECT.

SELECT
    campo1,
    campo2,
    (ST_Dump(ST_Union(t.geom))).geom as geom
FROM
    tabela_1 as t
GROUP BY
    campo1,
    campo2;

tabela1_union_by_value

Nota 1: Para quem prefere usar interfaces gráficos, preencher formulários e clicar em botões, o uso de SQL para fazer este tipo de operações pode parecer demasiado complicado e até um pouco retrógrado. Mas uma coisa garanto, com alguma prática as dificuldades iniciais são ultrapassadas e os benefícios que se retiram deste tipo de abordagem são muito recompensadores.

Nota 2: Visualizar o resultado deste tipos consultas de agregação (que usam a cláusula GROUP BY) no QGIS pode ser desafiante, este artigo explica como ultrapassar essa dificuldade.


Séries de mapas com formatos múltiplos em QGIS 2.6 – Parte 1 | Multiple format map series using QGIS 2.6 – Part 1

Para não variar, a nova versão do QGIS (o QGIS 2.6 Brigthon) traz um conjunto alargado de novas funcionalidades que permitem ao utilizador fazer mais, melhor e mais rápido do que com a versão anterior. Uma das novidades desta versão é a possibilidade de controlar algumas propriedades dos itens do compositor através de dados (por exemplo, o tamanho e a posição). Algo que abre a porta a aplicações bastante interessantes. Nos próximos artigos, proponho-me a mostrar como criar séries de mapas com multiplos formatos.

Like always, the new QGIS version (QGIS 2.6 Brigthon) brings a vast new set of features that will allow the user to do more, better and faster than with the earlier version. One of this features is the ability to control some of the composer’s items properties with data (for instance, size and position). Something that will allow lots of new interesting usages. In the next posts, I propose to show how to create map series with multiple formats.

Neste primeiro artigo, o objectivo é que, mantendo o tamanho da folha, o mapa seja criado com a orientação (paisagem ou retrato) que melhor se adapte à forma do elemento do atlas. Para exemplificar, usei a amostra de dados do Alaska para criar  um mapa de cada uma das regiões do Alaska.

In this first post, the goal is that, keeping the page size, the map is created with the most suitable orientation (landscape or portrait) to fit the atlas feature. To exemplify, I will be using the Alaska’s sample dataset to create a map for each of Alaska’s regions.

Em primeiro lugar comecei por criar o meu layout numa dos formatos, colocando vários itens nas posições que desejava.

I have started by creating the layout in one of the formats, putting the items in the desired positions.

mapa_base_atlas

Para  controlar a orientação da folha através do atlas, fui ao separador “Composição” e na opção orientação, usei no botão propriedades definidos por dados a seguinte expressão:

To control the page orientation with the atlas feature, in the composition tab, I used the following expression in the orientation data defined properties:

CASE WHEN bounds_width( $atlasgeometry ) >=  bounds_height( $atlasgeometry ) THEN 'landscape' ELSE 'portrait' END

Usando a opção de pré-visualização do atlas, podemos verificar que a orientação da folha já muda de acordo com a forma do elemento do atlas. No entanto, os itens não acompanham essa mudança e alguns ficam até fora da área de impressão.

Using the atlas preview, I could verify that the page’s orientation changed according to the form of the atlas feature. However, the composition’s items did not follow this change and some got even outside the printing area.

Screenshot from 2014-11-08 23:29:49

Para controlar o tamanho e posição dos itens do mapa tive em consideração o tamanho de uma folha A4 (297 x 210 mm), as dimensões das margens do mapa ( 20 mm, 5 mm, 10 mm, 5 mm) e os pontos de referência dos itens.

To control both size and position of the composition’s items I had in consideration the A4 page size (297 x 210 mm), the map margins ( 20 mm, 5 mm, 10 mm, 5 mm) and the item’s reference points.

No caso do item “mapa”, usando como ponto de referência o canto superior esquerdo, foi necessário alterar a sua altura e largura. Sabia que a altura do item era é subtracção do tamanho das margens superiores e inferiores (30 mm) da altura folha por isso a expressão a usar foi:

For the map item, using the upper left corner as reference point, it was necessary to change it’s height and width. I knew that the item height was the subtraction of the top and bottom margins (30 mm) from the page height, therefore I used the following expression:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 297 ELSE 210 END) - 30

De forma análoga, a expressão a usar para a largura foi:

Likewise, the expression to use in the width was:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 210 ELSE 297 END) - 10

Screenshot from 2014-11-09 00:02:15

Os restantes itens ocupavam sempre uma posição relativa na folha sem que fosse necessário alterar o seu tamanho e por isso tinha apenas de controlar a sua posição. Por exemplo, o título encontrava-se centrado no topo da folha, e portanto, usando como ponto de referência o topo-centro, bastou definir a seguinte expressão para a posição X:

The rest of the items were always at a relative position of the page without the need to change their size and therefore only needed to control their position. For example, the title was centered at the page’s top, and therefore, using the top-center as reference point, all that was needed was the following expression for the X position:

Screenshot from 2014-11-09 00:13:17

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry)  THEN 297 ELSE 210 END)  / 2.0

Screenshot from 2014-11-09 00:30:57

Já a legenda exige alterar a posição em X e em Y. Usando como ponto de referência o canto inferior direito, a expressão para a posição em X foi:
On the other hand, the legend needed to change the position in both X and Y. Using the bottom-right-corner as reference point, the X position expression was:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 297 ELSE 210 END) - 7

E para a posição em Y:
And for the Y position:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 210 ELSE 297 END) - 12

Screenshot from 2014-11-09 00:47:28

Para os restantes itens (rosa dos ventos, escala gráfica e texto no canto inferior esquerdo), as expressões a usar eram em tudo similares às já apresentadas, e, após definidas em cada um dos itens, fiquei com o layout preparado para se adaptar às duas orientações da folha.

For the remaining items (North arrow, scalebar, and bottom left text), the expression were similar to the ones already mentioned, and, after setting them for each item, I got a layout that would adapt to both page orientation

output_9

Depois disso, a impressão/exportação de todos os (25) mapas ficou à distância de um só clique.

From that point, printing/exporting all (25) maps was one click away.

mosaico_regioes

No próximo artigo da série, procurarei explicar como criar séries de mapas em que seja o tamanho da folha a adaptar-se de forma a manter uma escala constante.

In the next post of the serie, I will try to explain how to create map series where it’s the size of the page that change to keep the scale’s value of the scale constant.


Instalar duas versões de QGIS em Linux

QGIS24_QGISmaster

Em altura de testes à versão em desenvolvimento do QGIS (versão master), dá jeito  ter também instalada a última versão estável do QGIS. Em windows isso não representa um problema, uma vez que se podem instalar várias versões do QGIS em paralelo (tanto via Osgeo4w como standalone). Em linux, o processo não é tão directo pelo facto da instalação se realizar por obtenção de diversos pacotes disponíveis nos repositórios, não sendo por isso possível instalar mais do que uma versão sem que se originem quebras de dependências. Assim, instalando a versão estável através dos repositórios, as alternativas para instalação da versão em desenvolvimento são:

  • Compilar o QGIS master do código fonte;
  • Instalar o QGIS master num docker;
  • Instalar o QGIS master numa máquina virtual;

Neste artigo vou mostrar como compilar o código fonte em Ubuntu 14.04. Afinal não é tão difícil quanto parece. Meia dúzia de comandos e um pouco de paciência e vai-se lá. Usei como base as indicações do ficheiro INSTALL.TXT disponível no código fonte com umas pequenas alterações.

Instalar todas as dependências necessárias

Num terminal correr o seguinte comando para instalar todas as dependências e ferramentas necessárias à compilação do QGIS. (adicionei o ccmake e o git ao comando original)

sudo apt-get install bison cmake doxygen flex git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd pkg-config poppler-utils pyqt4-dev-tools python-all python-all-dev python-qt4 python-qt4-dev python-sip python-sip-dev spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui

Configurar o ccache

Este passo permite optimizar a compilação e tornar a compilação mais rápida nas próximas vezes que se fizer:

cd /usr/local/bin
sudo ln -s /usr/bin/ccache gcc
sudo ln -s /usr/bin/ccache g++

 Obter o código fonte do Github

O código fonte pode ser colocado numa pasta à escolha de cada um. Seguindo a sugestão do ficheiro de instruções acabei por colocar tudo na minha pasta home/alexandre/dev/cpp.

mkdir -p ${HOME}/dev/cpp
cd ${HOME}/dev/cpp

Já dentro da pasta home/alexandre/dev/cpp, podemos obter o código do qgis executando o seguinte comando git:

git clone git://github.com/qgis/QGIS.git

Nota: Se pretendesse fazer alterações ao código e experimentar se funcionava, então deveria fazer o clone do fork do qgis do meu próprio repositório, ou seja:

git clone https://github.com/SrNetoChan/Quantum-GIS

Preparar directorias de compilação e instalação

O código fonte tem de ser compilado e instalado em locais próprios para evitar conflitos com outras versões do QGIS. Por isso, há que criar uma pasta para efectuar a instalação:

mkdir -p ${HOME}/apps

E outra onde será feita a compilação:

cd QGIS
mkdir build-master
cd build-master

Configuração

Já na pasta build-master damos início ao processo de compilação. O primeiro passo é a configuração, onde vamos dizer onde queremos instalar o QGIS master. Para isso executamos o seguinte comando (não esquecer os dois pontos):

ccmake ..

Na configuração é necessário alterar o valor do CMAKE_INSTALL_PREFIX que define onde vai ser feita a instalação, no meu caso usei a pasta já criada ‘home/alexandre/apps’ . Para editar o valor há que mover o cursor até à linha em causa e carregar em [enter], depois de editar, volta-se a carregar em [enter]. Depois há que carregar em [c] para refazer a configuração e depois em ‘g’ para gerar a configuração.

Screenshot from 2014-10-08 23:33:39

 Compilação e instalação

Já com tudo configurado resta compilar o código e depois instalá-lo:

make
sudo make install

Nota: Estes dois passos podem demorar um bocadinho, principalmente na primeira vez que o código for compilado.

Depois de instalado podemos correr o QGIS master a partir da pasta de instalação:

cd ${HOME}/apps/bin/
export LD_LIBRARY_PATH=/home/alexandre/apps/lib
export QGIS_PREFIX_PATH=/home/alexandre/apps
${HOME}/apps/bin/qgis

Para se tornar mais cómodo, podemos colocar os últimos 3 comandos num ficheiro .sh e gravá-lo num local acessível (desktop ou home) para executarmos o qgis sempre que necessário.

Screenshot from 2014-10-09 00:36:52

UPDATE: Actualizar a versão master

Como já foi referido num comentário, a versão em desenvolvimento está constantemente a ser alterada, por isso para testar se determinados bugs foram entretanto corrigidos há que a actualizar. Trata-se de um processo bastante simples. O primeiro passo é actualizar o código fonte:

cd ${HOME}/dev/cpp/qgis
git pull origin master

E depois é voltar a correr a compilação (que desta feita será mais rápida):

cd build-master
ccmake ..
make
sudo make install

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.


Use o operador “IN” sff | Please use the “IN” operator

Já não é a primeira vez que vejo pessoas que para seleccionarem elementos pelos valores dos seus atributos, usam expressões como:

It’s not the first time that I see people that, to select feature by their fields values use expressions like this:

"field" = 'value1' OR "field" = 'value2' OR "field" = 'value3' [OR ...]

Uma forma mais prática e bonita de o fazer é usar o operador IN.

A more practical and pretty way of doing this is by using the IN operator instead.

"field" IN ('value1','value2','value3'[,...])

Este operador existe em quase todos os softwares SIG que conheço. No QGIS, pode ser usado mesmo quando não existe um botãozinho para clicar.

This operator is available in almost every GIS software I know. In QGIS, it can be used even if there isn’t a small little button to click.
Captura de tela 2014-04-23 16.50.40

Na verdade, trata-se de uma abreviatura do que é usado em SQL, onde o operador é usado na expressão WHERE.

In fact, this is an abbreviation of what is used in SQL, where the operator is used in the WHERE statement:

SELECT *
FROM parks
WHERE "tipo" IN ('PI','CM','PJ');

  • Page 1 of 2 ( 34 posts )
  • >>
  • uncategorized

Back to Top

Sponsors