QGIS uses the OGR library to read and write vector data formats including ESRI Shapefiles, MapInfo, Microstation file formats and many more. GRASS vector, PostGIS, MSSQL Spatial and Oracle Spatial support is supplied by native QGIS data providers. Vector data can also be loaded in read mode from zip and gzip archives into QGIS. At the date of this document, 69 vector formats are supported by the OGR library (see OGR-SOFTWARE-SUITE Referências Bibliográficas e Web). The complete list of supported vector data formats by the OGR library (see OGR-SOFTWARE-SUITE Referências Bibliográficas e Web) is available at http://www.gdal.org/ogr/ogr_formats.html.
Nota
Not all of the listed formats may work in QGIS for various reasons. For example, some require external commercial libraries or the GDAL/OGR installation of your OS was not build to support the format you want to use. Only those formats that have been well tested will appear in the list of file types when loading a vector into QGIS. Other untested formats can be loaded by selecting *.*.
Procedimentos com dados vetoriais GRASS são descritos na Seção Integração com SIG GRASS.
This section describes how to work with several common formats: ESRI Shapefiles, PostGIS layers, SpatiaLite layers, OpenStreetMap vectors etc. Many of the features available in QGIS work the same, regardless of the vector data source. This is by design and includes the identify, select, labeling and attributes functions.
O formato de arquivo vetorial padrão usado pelo QGIS é o Shapefile ESRI. O suporte é fornecido pela Livraria OGR Simple Feature ( http://www.gdal.org/ogr/ ).
Um shapefile consiste na verdade de um conjunto de vários arquivos. Os três seguintes são necessários:
.shp arquivo que contém as formas vetoriais.
.dbf arquivo que contém os atributos no formato dBase..
.shx arquivos indicadores.
Shapefiles também podem incluir um arquivo com a extensão .prj que contém as informações de projeção. Embora seja muito útil um arquivo de projeção, não é obrigatória. Um conjunto de dados shapefile pode conter arquivos adicionais. Para mais detalhes veja a especificação técnica ESRI em: http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf.
To load a shapefile, start QGIS and click on the
Add Vector Layer toolbar button or simply type Ctrl+Shift+V.
This will bring up a new window (see figure_vector_1).
Figure Vector 1:
From the available options check File. Click on button
[Browse]. That will bring up a standard open file dialog (see figure_vector_2)
which allows you to navigate the file system and load a shapefile or other
supported data source. The selection box Filter
allows
you to preselect some OGR supported file formats.
Você também pode selecionar o tipo de codificação para o shapefile, se desejar.
Figure Vector 2:
Ao selecinar um shapefile a partir da lista e clicando em [Abrir] o QGIS o carregará. A Figure_vector_3 exibe o QGIS depois de carregar o arquivo alaska.shp.
Figure Vector 3:
Dica
Cores das camadas
Quando você adiciona uma camada ao mapa, é atribuída uma cor aleatória. Na adição de mais de uma camada de uma vez, são atribuídas cores diferentes para cada camada.
Once loaded, you can zoom around the shapefile using the map navigation tools. To change the style of a layer, open the Layer Properties dialog by double clicking on the layer name or by right-clicking on the name in the legend and choosing Properties from the popup menu. See Section Style Menu for more information on setting symbology of vector layers.
Dica
Carregando camadas e armazenando projetos em unidades externas no OS X
No OS X, unidades portáteis que são armazenadas além do disco rígido principal não aparecem no File ‣Open Project `como esperado. Para resolver isso estamos trabalhando em uma forma mais nativa do OS X com caixa de diálogo abrir/salvar. Como alternativa, você pode digitar ‘/Volumes’ no campo Nome do arquivo e pressione :kbd:`Voltar. Depois, você pode navegar para unidades externas ou armazenadas em rede.
Para melhorar o desempenho do desenho de um shapefile, você pode criar um índice espacial. Um índice espacial irá melhorar a velocidade do zoom e visão panorâmica. Os índices espaciais utilizados pelo QGIS estão na extensão .qix.
Siga estes passos para criar o índice:
Abra a caixa de diálogo Propriedades da camada clicando duas vezes sobre o nome do shapefile na legenda ou com o botão direito do mouse e escolha Propriedades a partir do menu pop-up.
Na guia :guilabel:’Geral’, clique no botão [Criar índice espacial].
If you load a shapefile with .prj file and QGIS is not able to read the coordinate reference system from that file, you have to define the proper projection manually within the General tab of the Layer Properties dialog of the layer by clicking the [Specify...] button. This is due to the fact, that .prj files often do not provide the complete projection parameters, as used in QGIS and listed in the CRS dialog.
Por essa razão, se você criar um novo shapefile no QGIS, dois arquivos de projeção diferentes são criados. Um arquivo .prj com os parâmetros limitados de projeção, compatível com o software ESRI, e um arquivo .qpj, fornecendo os parâmetros completos dos CRS usados. Se o QGIS encontra um arquivo .qpj, ele será usado em vez do arquivo prj.
To load a MapInfo layer, click on the
Add Vector Layer toolbar button or type Ctrl+Shift+V, change the
file type filter Filter
: to ‘Mapinfo File [OGR]’ and
select the MapInfo layer you want to load.
To load an ArcInfo binary coverage, click on the
Add Vector Layer toolbar button or press Ctrl+Shift+V to open the
Add Vector Layer dialog. Select
Directory.
Change to Filter
to ‘Arc/Info Binary Coverage’.
Navigate to the directory that contains the coverage files and select it.
Da mesma forma, você pode carregar arquivos vetoriais baseados em um diretório no formato UK National Transfer, bem como os formatos TIGER do Census Bureau US.
QGIS integrates Openstreetmap import as a core functionnality.
Camadas PostGIS são armazenados em um banco de dados PostgreSQL. As vantagens do PostGIS são a indexação espacial, filtragem e recursos de consulta. Usando o PostGIS, funções vetoriais, como selecionar e identificar permitem um trabalho com mais precisão do que com camadas OGR no QGIS.
The first time you use a PostGIS data source, you must create
a connection to the PostgreSQL database that contains the data. Begin by clicking
on the
Add PostGIS Layer toolbar button, selecting the
Add PostGIS Layer... option from the
Layer menu or typing Ctrl+Shift+D. You can also open the
Add Vector Layer dialog and select
Database.
The Add PostGIS Table(s) dialog will be displayed. To access the
connection manager, click on the [New] button to display the
Create a New PostGIS Connection dialog. The parameters required for
a connection are:
desabilitar: apenas tentar uma conexão SSL não criptografada
permitir: tentar uma conexão não-SSL, se isso falhar, tente uma conexão SSL
preferir (por padrão): tentar uma conexão SSL, se isso falhar, tentar uma conexão não-SSL;
requer: só tentar uma conexão SSL.
Opcionalmente você pode ativar as seguintes caixas de seleção:
:guilabel:`Apenas olhar no esquema ‘público’
Uma vez que todos os parâmetros e as opções estão configuradas, você pode testar a conexão clicando no botão [Testar Conexão].
Dica
QGIS Configurações do Usuário e Segurança
Depending on your computing environment, storing passwords in your QGIS settings may be a security risk. Your customized settings for QGIS are stored based on the operating system:
Once you have one or more connections defined, you can load
layers from the PostgreSQL database. Of course this requires having data in
PostgreSQL. See Section Importação de dados no PostgreSQL for a discussion on
importing data into the database.
Para colocar uma camada no PostGIS, execute os seguintes passos:
Escolha a conexão a partir da lista drop-down e clique em [Conectar].
Encontre a camada(s) que deseja adicionar na lista de camadas disponíveis.
Selecione-a clicando sobre ela. Você pode selecionar várias camadas pressionando a tecla Shift enquanto clica. Consulte a Seção Query Builder para obter informações sobre como usar o Query Builder PostgreSQL para melhor definição da camada.
Clique no botão [Add] para adicionar a camada ao mapa.
Dica
Camadas PostGIS
Normalmente uma camada PostGIS é definida por um caminho na tabela. A partir da versão 0.9.0 em diante, o QGIS permite carregar camadas que não têm um caminho na tabela geometry_columns. Isto inclui ambas as tabelas e exibições. A definição de uma visão espacial fornece um meio poderoso para visualizar seus dados. Consulte o manual do PostgreSQL para obter informações sobre a criação de pontos de vista diversos.
Esta seção contém alguns detalhes sobre como o QGIS acessa camadas do PostgreSQL. Na maioria das vezes o QGIS simplesmente deve fornecer-lhe uma lista de tabelas do banco de dados que podem ser carregadas, e carregá-las mediante solicitação. No entanto, se você tiver problemas para carregar uma tabela do PostgreSQL no QGIS, as informações abaixo podem ajudá-lo a entender as mensagens do QGIS e dar-lhe orientações para alterar a tabela de PostgreSQL ou ver definições para permitir o QGIS carregá-la.
O QGIS requer que as camadas PostgreSQL contenham uma coluna que pode ser usada como uma chave única para a camada. Para tabelas, isso geralmente significa que a tabela precisa de uma chave primária, ou uma coluna com uma restrição exclusiva sobre ela. No QGIS, esta coluna tem de ser do tipo int4 (um inteiro de 4 bytes). Alternativamente, a coluna ctid pode ser usada como chave primária. Se uma tabela não tem esses itens, a coluna oid será usado em seu lugar. O desempenho será melhorado se a coluna é indexada (note que as chaves primárias são automaticamente indexadas pelo PostgreSQL).
If the PostgreSQL layer is a view, the same requirement exists, but views do not have primary keys or columns with unique constraints on them. You have to define a primary key field (has to be integer) in the QGIS dialog before you can load the view. If a suitable column cannot does not exist in the view, QGIS will not load the layer. If this occurs, the solution is to alter the view so that it does include a suitable column (a type of integer and either a primary key or with a unique constraint, preferably indexed).
QGIS offers a checkbox Select at id that is activated by default. This option gets the ids without the attributes which is faster in most cases. It can make sense to disable this option when you use expensive views.
Data can be imported into PostgreSQL/PostGIS using several tools, such as the SPIT plugin or the command line tools shp2pgsql or ogr2ogr.
QGIS comes with a core plugin named DB Manager. It can be used to
load shapefiles and other data formats and includes support for schemas. See Section
DB Manager Plugin for more information.
PostGIS includes an utility called shp2pgsql that can be used to import shapefiles into a PostGIS enabled database. For example, to import a shapefile named lakes.shp into a PostgreSQL database named gis_data, use the following command:
shp2pgsql -s 2964 lakes.shp lakes_new | psql gis_data
Isso cria uma nova camada chamada lakes_new no banco de dados gis_data. A nova camada terá um identificador de referência espacial (SRID) de 2964. Consulte a Seção Trabalhando com Projeções para mais informações sobre os sistemas de referência espacial e projeções.
Dica
Exportando conjuntos de dados do PostGIS
Assim como a ferramenta de importação shp2pgsql, há também uma ferramenta para exportar conjuntos de dados PostGIS como shapefiles: pgsql2shp. Este é enviado dentro de sua distribuição PostGIS.
Beside shp2pgsql and DB Manager there is another tool for feeding geodata in PostGIS: ogr2ogr. This is part of your GDAL installation.
Para importar um shapefile no PostGIS, faça o seguinte :
ogr2ogr -f "PostgreSQL" PG:"dbname=postgis host=myhost.de user=postgres \
password=topsecret" alaska.shp
Isto irá importar o shapefile alaska.shp para o banco de dados PostGIS postgis usando o usuário postgres com a senha topsecret no servidor myhost.de.
Note que o OGR deve ser construído com PostgreSQL para suportar PostGIS. Você pode ver isso digitando
ogrinfo --formats | grep -i post
Se você gosta de usar o comando PostgreSQL COPY em vez do método padrão INSERT INTO, você pode exportar a seguinte variável no ambiente (pelo menos disponível no e
):
export PG_USE_COPY=YES
O ogr2ogr não cria índices espaciais como faz o shp2pgsl. Você precisa criá-los manualmente, normalmente usando o comando SQL CREATE INDEX como um passo extra (como descrito na próxima seção melhorando o Desempenho).
Retrieving features from a PostgreSQL database can be time consuming, especially over a network. You can improve the drawing performance of PostgreSQL layers by ensuring that a PostGIS spatial index exists on each layer in the database. PostGIS supports creation of a GiST (Generalized Search Tree) index to speed up spatial searches of the data (GiST index information is taken from the PostGIS documentation available at http://postgis.refractions.net).
The syntax for creating a GiST index is:
CREATE INDEX [indexname] ON [tablename]
USING GIST ( [geometryfield] GIST_GEOMETRY_OPS );
Observe que para grandes tabelas, a criação do índice pode levar um longo tempo. Uma vez que o índice é criado, você deve realizar um VACUUM ANALYZE. Consulte a documentação do PostGIS (PostGIS-PROJECT Referências Bibliográficas e Web) para mais informações.
A seguir um exemplo de criação de um índice GiST:
gsherman@madison:~/current$ psql gis_data
Welcome to psql 8.3.0, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
gis_data=# CREATE INDEX sidx_alaska_lakes ON alaska_lakes
gis_data-# USING GIST (the_geom GIST_GEOMETRY_OPS);
CREATE INDEX
gis_data=# VACUUM ANALYZE alaska_lakes;
VACUUM
gis_data=# \q
gsherman@madison:~/current$
Many GIS packages don’t wrap vector maps, with a geographic reference system (lat/lon), crossing the 180 degrees longitude line (http://postgis.refractions.net/documentation/manual-1.4/ST_Shift_Longitude.html). As result, if we open such map in QGIS, we will see two far, distinct locations, that should show near each other. In Figure_vector_4 the tiny point on the far left of the map canvas (Chatham Islands), should be within the grid, right of New Zealand main islands.
Figure Vector 4:
A workaround is to transform the longitude values using PostGIS and the ST_Shift_Longitude function This function reads every point/vertex in every component of every feature in a geometry, and if the longitude coordinate is < 0° adds 360° to it. The result would be a 0° - 360° version of the data to be plotted in a 180° centric map.
Figure Vector 5:
Import data to PostGIS (Importação de dados no PostgreSQL) using for example the DB Manager plugin.
Use a interface de linha de comando PostGIS para emitir o seguinte comando (este é um exemplo onde a “TABLE” é o nome real da sua tabela no PostGIS)
gis_data=# update TABLE set the_geom=ST_Shift_Longitude(the_geom);
Se tudo correu bem, você deve receber uma confirmação sobre o número de feições que foram atualizadas, então você vai ser capaz de carregar o mapa, veja a diferença (Figure_vector_5)
A primeira vez que você carregar dados de um banco de dados SpatiaLite, comece clicando no botão
:sup: Adicionar Camada SpatiaLite na barra de ferramentas ou selecione a opção
:menuselection:’Adicionar Camada SpatiaLite ... no menu Camada ou digitando Ctrl+Shift+L. Isso fará com que surja uma janela, que permitirá você se conectar a um banco de dados SpatiaLite já identificado no QGIS, que você pode escolher no menu suspenso ou para definir uma nova conexão para um novo banco de dados. Para definir uma nova conexão, clique em [New] e use o navegador de arquivos para apontar para o banco de dados SpatiaLite, que é um arquivo com extensão .sqlite.
If you want to save a vector layer to SpatiaLite format you can do this by right clicking the layer in the legend. Then click on Save as.., define the name of the output file, select ‘SpatiaLite’ as format and the CRS. Also you can select ‘SQLite’ as format, and then add SPATIALITE=YES in the OGR data source creation option field. This tells OGR to create a SpatiaLite database. See also http://www.gdal.org/ogr/drv_sqlite.html.
QGIS also supports editable views in SpatiaLite.
Se você quiser criar uma nova camada SpatiaLite, consulte a seção Criando uma nova camada SpatiaLite.
Dica
Gestão complementos de dados SpatiaLite
For SpatiaLite data management you can also use several Python plugins: QSpatiaLite, SpatiaLite Manager or DB Manager (core plugin, recommended). They can be downloaded and installed with the Plugin Installer.
QGIS also provides native MS SQL 2008 support. The
Add MSSQL Spatial Layer is part of the new toolbar
button or available in the MS SQL node in the QBrowser tree, providing drag and
drop import support.
QGIS also provides native ORACLE Locator/Spatial support. The
Add ORACLE Spatial Layer is part of the new toolbar
button or available in the ORACLE node in the QBrowser tree, providing drag and
drop import support. ORACLE Spatial layers are stored in an ORACLE database.
The first time you use a ORACLE Spatial data source, you must create
a connection to the database that contains the data. Begin by clicking
on the
Add ORACLE Spatial Layer toolbar button, selecting the
Add ORACLE Spatial Layer... option from the
Layer menu or typing Ctrl+Shift+O. To access the
connection manager, click on the [New] button to display the
Create a New ORACLE Spatial Connection dialog. The parameters required for
a connection are:
Opcionalmente você pode ativar as seguintes caixas de seleção:
Uma vez que todos os parâmetros e as opções estão configuradas, você pode testar a conexão clicando no botão [Testar Conexão].
Dica
QGIS Configurações do Usuário e Segurança
Depending on your computing environment, storing passwords in your QGIS settings may be a security risk. Passwords are saved in clear text in the system configuration and in the project files! Your customized settings for QGIS are stored based on the operating system:
Once you have one or more connections defined, you can load
layers from the ORACLE database. Of course this requires having data in
ORACLE.
To load a layer from ORACLE Spatial, perform the following steps:
Escolha a conexão a partir da lista drop-down e clique em [Conectar].
Encontre a camada(s) que deseja adicionar na lista de camadas disponíveis.
Clique no botão [Add] para adicionar a camada ao mapa.
Dica
ORACLE Spatial Layers
Normally an ORACLE Spatial layer is defined by an entry in the USER_SDO_METADATA table.