Importante
A tradução é um esforço comunitário você pode contribuir. Esta página está atualmente traduzida em 37.97%.
15.3. Explorando Formatos de Dados e Campos
15.3.1. Dados raster
GIS raster data are matrices of discrete cells that represent features / phenomena on, above or below the earth’s surface. Each cell in the raster grid has the same size, and cells are usually rectangular (in QGIS they will always be rectangular). Typical raster datasets include remote sensing data, such as aerial photography, or satellite imagery and modelled data, such as elevation or temperature.
Ao contrário dos dados vetoriais, os dados matriciais normalmente não possuem um registro de banco de dados associado para cada célula. Eles são geocodificados pela resolução do pixel e pela coordenada X/Y de um pixel de canto da camada matricial. Isso permite que o QGIS posicione os dados corretamente na tela do mapa.
The GeoPackage format is convenient for storing raster data when working with QGIS. The popular and powerful GeoTiff format is a good alternative.
QGIS makes use of georeference information inside the raster layer (e.g., GeoTiff) or an associated world file to properly display the data.
15.3.2. Dado Vetorial
Many of the features and tools available in QGIS work the same, regardless the vector data source. However, because of the differences in format specifications (GeoPackage, ESRI Shapefile, MapInfo and MicroStation file formats, AutoCAD DXF, PostGIS, SpatiaLite, Oracle Spatial, MS SQL Server, SAP HANA Spatial databases and many more), QGIS may handle some of their properties differently. Support is provided by the GDAL vector drivers. This section describes how to work with these specifics.
Nota
QGIS supports (multi)point, (multi)line, (multi)polygon, CircularString, CompoundCurve, CurvePolygon, MultiCurve, MultiSurface feature types, all optionally with Z and/or M values.
You should also note that some drivers don’t support some of these feature types, like CircularString, CompoundCurve, CurvePolygon, MultiCurve, MultiSurface feature type. QGIS will convert them.
15.3.2.1. GeoPackage
The GeoPackage (GPKG) format is platform-independent, and is implemented as a SQLite database container, and can be used to store both vector and raster data. The format was defined by the Open Geospatial Consortium (OGC), and was published in 2014.
GeoPackage can be used to store the following in a SQLite database:
vector features
tile matrix sets of imagery and raster maps
atributos (dados não espaciais)
extensões
Since QGIS version 3.8, GeoPackage can also store QGIS projects. GeoPackage layers can have JSON fields.
GeoPackage é o formato padrão para dados vetoriais no QGIS.
15.3.2.2. ESRI Shapefile format
The ESRI Shapefile format is still one of the most used vector file formats, even if it has some limitations compared to for instance GeoPackage and SpatiaLite.
An ESRI Shapefile format dataset consists of several files. The following three are required:
.shp
file containing the feature geometries.dbf
arquivo que contém os atributos no formato dBase.shx
index file
An ESRI Shapefile format dataset can also include a file with a
.prj
suffix, which contains projection information.
While it is very useful to have a projection file, it is not
mandatory.
A Shapefile format dataset can contain additional files.
For further details, see the the ESRI technical specification.
GDAL has read-write support for compressed ESRI Shapefile
format (shz
and shp.zip
).
Improving Performance for ESRI Shapefile format datasets
To improve the drawing performance for an ESRI Shapefile format
dataset, you can create a spatial index.
A spatial index will improve the speed of both zooming and panning.
Spatial indexes used by QGIS have a .qix
extension.
Usar estas etapas para criar o índice:
Load an ESRI Shapefile format dataset (see The Browser Panel)
Abra a caixa de diálogo Propriedades da Camada clicando duas vezes no nome da camada na legenda ou clicando com o botão direito do mouse e escolhendo no menu de contexto
In the Source tab, click the Create Spatial Index button
Problema ao carregar um arquivo .prj
If you load an ESRI Shapefile format dataset with a .prj
file
and QGIS is not able to read the coordinate reference system from
that file, you will need to define the proper projection manually in
the tab of the layer by
clicking the Select CRS 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.
For the same reason, if you create a new ESRI Shapefile format dataset
with QGIS, two different projection files are created: a .prj
file with limited projection parameters, compatible with ESRI
software, and a .qpj
file, providing all the parameters of the
CRS.
Whenever QGIS finds a .qpj
file, it will be used instead of
the .prj
.
15.3.2.3. Delimited Text Files
Arquivos de texto delimitados são muito comuns e amplamente utilizados devido à sua simplicidade e legibilidade - os dados podem ser visualizados e editados em um editor de texto simples. Um arquivo de texto delimitado é um dado de tabela com colunas separadas por um caractere definido e linhas separadas por quebras de linha. A primeira linha geralmente contém os nomes das colunas. Um tipo comum de arquivo de texto delimitado é um CSV (Comma Separated Values), com colunas separadas por vírgulas. Arquivos de texto delimitados também podem conter informações posicionais (veja Armazenando informações de geometria em arquivos de texto delimitados).
QGIS allows you to load a delimited text file as a layer or an ordinary table (see The Browser Panel or Importando um arquivo de texto delimitado). First check that the file meets the following requirements:
O arquivo deve ter uma linha de cabeçalho delimitada de nomes de campo. Esta deve ser a primeira linha dos dados (de preferência a primeira linha no arquivo de texto).
Se a geometria deve ser habilitada, o arquivo deve conter campos que definem a geometria. Esses campos podem ter qualquer nome.
Os campos de coordenadas X e Y (se a geometria for definida por coordenadas) devem ser especificados como números. O sistema de coordenadas não é importante.
If you have a CSV file with non-string columns, you can have an accompanying CSVT file (see section Using CSVT file to control field formatting).
The elevation point data file elevp.csv
in the QGIS sample
dataset (see section Baixando dados de amostra) is an example of a
valid text file:
X;Y;ELEV
-300120;7689960;13
-654360;7562040;52
1640;7512840;3
[...]
Algumas coisas a serem observadas sobre o arquivo de texto:
O arquivo de texto de exemplo usa
;
(ponto e vírgula) como delimitador (qualquer caractere pode ser usado para delimitar os campos).A primeira linha é a linha de cabeçalho. Ela contém os campos
X
,Y
eELEV
.No quotes (
"
) are used to delimit text fieldsAs coordenadas X estão contidas no campo
X
As coordenadas Y estão contidas no campo
Y
Armazenando informações de geometria em arquivos de texto delimitados
Arquivos de texto delimitados podem conter informações de geometria em duas formas principais:
Como coordenadas em colunas separadas (ex.
Xcol
,Ycol
… ), para dados de geometria de ponto;As well-known text (WKT) representation of geometry in a single column, for any geometry type.
Features with curved geometries (CircularString, CurvePolygon and CompoundCurve) are supported. Here are some examples of geometry types in a delimited text file with geometries coded as WKT:
Label;WKT_geom
LineString;LINESTRING(10.0 20.0, 11.0 21.0, 13.0 25.5)
CircularString;CIRCULARSTRING(268 415,227 505,227 406)
CurvePolygon;CURVEPOLYGON(CIRCULARSTRING(1 3, 3 5, 4 7, 7 3, 1 3))
CompoundCurve;COMPOUNDCURVE((5 3, 5 13), CIRCULARSTRING(5 13, 7 15,
9 13), (9 13, 9 3), CIRCULARSTRING(9 3, 7 1, 5 3))
Arquivos de texto delimitados também suportam coordenadas Z e M em geometrias:
LINESTRINGZ(10.0 20.0 30.0, 11.0 21.0 31.0, 11.0 22.0 30.0)
Using CSVT file to control field formatting
When loading CSV files, the GDAL driver assumes all fields are strings (i.e. text) unless it is told otherwise. You can create a CSVT file to tell GDAL (and QGIS) the data type of the different columns:
Tipo |
Nome |
Exemplo |
---|---|---|
Número inteiro |
Número inteiro |
4 |
Booleano |
Integer(Boolean) |
true |
Número decimal |
Real |
3.456 |
Data |
Data (AAAA-MM-DD) |
2016-07-28 |
Hora |
Hora (HH:MM:SS+nn) |
18:33:12+00 |
Data & Hora |
DateTime (YYYY-MM-DD HH:MM:SS+nn) |
2016-07-28 18:33:12+00 |
CoordX |
CoordX |
8.8249 |
CoordY |
CoordY |
47.2274 |
Point(X) |
Point(X) |
8.8249 |
Point(Y) |
Point(Y) |
47.2274 |
WKT |
WKT |
POINT(15 20) |
The CSVT file is a ONE line plain text file with the data types in quotes and separated by commas, e.g.:
"Integer","Real","String"
Você pode até especificar a largura e a precisão de cada coluna, por exemplo:
"Integer(6)","Real(5.5)","String(22)"
Este arquivo é salvo na mesma pasta que o arquivo .csv
, com o mesmo nome, mas .csvt
como a extensão.
*Você pode encontrar mais informações em * GDAL CSV Driver.
Dica
Detect Field Types
Instead of using a CSVT file to tell the data types, QGIS provides the possibility to automatically detect the field types and to change the assumed field types.
15.3.2.4. Camadas PostGIS
PostGIS layers are stored in a PostgreSQL database. The advantages of PostGIS are spatial indexing, filtering and querying capabilities. Using PostGIS, vector functions such as select and identify work more accurately than they do with GDAL layers in QGIS.
Dica
Camadas PostGIS
Normalmente, uma camada PostGIS é identificada por uma entrada na tabela de geometria_colunas. QGIS pode carregar camadas que não têm uma entrada na tabela de geometria_colunas. Isto inclui tanto as tabelas quanto as vistas. Consulte seu manual PostgreSQL para obter informações sobre como criar vistas.
This section contains some details on how QGIS accesses PostgreSQL layers. Most of the time, QGIS should simply provide you with a list of database tables that can be loaded, and it will load them on request. However, if you have trouble loading a PostgreSQL table into QGIS, the information below may help you understand QGIS messages and give you directions for modifying the PostgreSQL table or view definition to allow QGIS to load it.
Nota
Um banco de dados PostgreSQL também pode armazenar projetos QGIS.
Chave primária
QGIS requires that PostgreSQL layers contain a column that can be used as a unique key for the layer. For tables, this usually means that the table needs a primary key, or a column with a unique constraint on it. In QGIS, this column needs to be of type int4 (an integer of size 4 bytes). Alternatively, the ctid column can be used as primary key. If a table lacks these items, the oid column will be used instead. Performance will be improved if the column is indexed (note that primary keys are automatically indexed in PostgreSQL).
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.
Ver
Se a camada do PostgreSQL é uma visualização, o mesmo requisito existe, mas as visualizações nem sempre possuem chaves ou colunas primárias com restrições exclusivas. Você precisa definir um campo de chave primária (deve ser inteiro) na caixa de diálogo QGIS antes de poder carregar a exibição. Se uma coluna adequada não existir na exibição, o QGIS não carregará a camada. Se isso ocorrer, a solução é alterar a exibição para incluir uma coluna adequada (um tipo de número inteiro e uma chave primária ou com uma restrição exclusiva, preferencialmente indexada).
As for table, a checkbox Select at id is activated by default (see above for the meaning of the checkbox). It can make sense to disable this option when you use expensive views.
Nota
PostgreSQL foreign table
PostgreSQL foreign tables are not explicitely supported by the PostgreSQL provider and will be handled like a view.
QGIS layer_style table and database backup
If you want to make a backup of your PostGIS database using the
pg_dump
and pg_restore
commands, and the default layer
styles as saved by QGIS fail to restore afterwards, you need to set
the XML option to DOCUMENT
before the restore command:
Fazer um backup SIMPLES da tabela
layer_style
Abrir o arquivo dentro de um editor de texto
Mude a linha
SET xmloption = content;
paraSET XML OPTION DOCUMENT;
Salvar o arquivo
Use psql para restaurar a tabela no novo banco de dados
Filter database side
QGIS allows to filter features already on server side. Check to do so. Only supported expressions will be sent to the database. Expressions using unsupported operators or functions will gracefully fallback to local evaluation.
Support of PostgreSQL data types
Data types supported by the PostgreSQL provider include: integer, float, boolean, binary object, varchar, geometry, timestamp, array, hstore and json.
15.3.2.5. Importing Data into PostgreSQL
Data can be imported into PostgreSQL/PostGIS using several tools, including the DB Manager plugin and the command line tools shp2pgsql and ogr2ogr.
Gerenciador BD
O QGIS vem com um complemento principal chamado Gerenciador de BD. Ele pode ser usado para carregar dados e inclui suporte para esquemas. Veja a seção Plugin do gerenciador de banco de dados para mais informações.
shp2pgsql
PostGIS includes a utility called shp2pgsql, that can be used to import
Shapefile format datasets into a PostGIS-enabled database.
For example, to import a Shapefile format dataset named
lakes.shp
into a PostgreSQL database named gis_data
, use
the following command:
shp2pgsql -s 2964 lakes.shp lakes_new | psql gis_data
This creates a new layer named lakes_new
in the gis_data
database.
The new layer will have a spatial reference identifier (SRID) of 2964.
See section Trabalhando com Projeções for more information about spatial
reference systems and projections.
Dica
Exporting datasets from PostGIS
There is also a tool for exporting PostGIS datasets to Shapefile format: pgsql2shp. It is shipped within your PostGIS distribution.
ogr2ogr
In addition to shp2pgsql and DB Manager, there is another tool for feeding geographical data in PostGIS: ogr2ogr. It is part of your GDAL installation.
To import a Shapefile format dataset into PostGIS, do the following:
ogr2ogr -f "PostgreSQL" PG:"dbname=postgis host=myhost.de user=postgres
password=topsecret" alaska.shp
This will import the Shapefile format dataset alaska.shp
into the
PostGIS database postgis using the user postgres with the password
topsecret on the host server myhost.de.
Note that GDAL must be built with PostgreSQL to support PostGIS. You can verify this by typing (in ):
ogrinfo --formats | grep -i post
If you prefer to use the PostgreSQL’s COPY command instead of the default INSERT INTO method, you can export the following environment variable (at least available on and ):
export PG_USE_COPY=YES
ogr2ogr does not create spatial indexes like shp2pgsl does. You need to create them manually, using the normal SQL command CREATE INDEX afterwards, as an extra step (as described in the next section Melhorando a Performance).
Melhorando a Performance
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 searching (GiST index information is taken from the PostGIS documentation available at https://postgis.net).
Dica
You can use the DBManager to create an index for your layer. You should first select the layer and click on Add Spatial Index.
, go to tab and click onThe syntax for creating a GiST index is:
CREATE INDEX [indexname] ON [tablename]
USING GIST ( [geometryfield] GIST_GEOMETRY_OPS );
Note that for large tables, creating the index can take a long time.
Once the index is created, you should perform a VACUUM ANALYZE
.
See the PostGIS documentation (POSTGIS-PROJECT in
Referências Bibliográficas e Web) for more information.
The following example creates a GiST index:
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 (geom GIST_GEOMETRY_OPS);
CREATE INDEX
gis_data=# VACUUM ANALYZE alaska_lakes;
VACUUM
gis_data=# \q
gsherman@madison:~/current$
15.3.2.6. Camadas SpatiaLite
If you want to save a vector layer using the SpatiaLite format, you
can do this by following instructions at Criando novas camadas a partir de uma camada existente.
You select SpatiaLite
as Format and
enter both File name and Layer name.
Also, you can select SQLite
as format and then add
SPATIALITE=YES
in the
field.
This tells GDAL to create a SpatiaLite database.
See also https://gdal.org/drivers/vector/sqlite.html.
QGIS also supports editable views in SpatiaLite. For SpatiaLite data management, you can also use the core plugin DB Manager.
Se você deseja criar uma nova camada SpatiaLite, por favor consulte a seção Creating a new SpatiaLite layer.
15.3.2.7. GeoJSON specific parameters
When exporting layers to GeoJSON, there are some specific Layer Options available. These options come from GDAL which is responsible for the writing of the file:
COORDINATE_PRECISION the maximum number of digits after the decimal separator to write in coordinates. Defaults to 15 (note: for Lat Lon coordinates 6 is considered enough). Truncation will occur to remove trailing zeros.
RFC7946 by default GeoJSON 2008 will be used. If set to YES, the updated RFC 7946 standard will be used. Default is NO (thus GeoJSON 2008). See https://gdal.org/drivers/vector/geojson.html#rfc-7946-write-support for the main differences, in short: only EPSG:4326 is allowed, other crs’s will be transformed, polygons will be written such as to follow the right-hand rule for orientation, values of a “bbox” array are [west, south, east, north], not [minx, miny, maxx, maxy]. Some extension member names are forbidden in FeatureCollection, Feature and Geometry objects, the default coordinate precision is 7 decimal digits
WRITE_BBOX set to YES to include the bounding box of the geometries at the feature and feature collection level
Besides GeoJSON there is also an option to export to “GeoJSON - Newline Delimited” (see https://gdal.org/drivers/vector/geojsonseq.html). Instead of a FeatureCollection with Features, you can stream one type (probably only Features) sequentially separated with newlines.
GeoJSON - Newline Delimited has some specific Layer options availabe too:
COORDINATE_PRECISION see above (same as for GeoJSON)
RS whether to start records with the RS=0x1E character. The difference is how the features are separated: only by a newline (LF) character (Newline Delimited JSON, geojsonl) or by also prepending a record-separator (RS) character (giving GeoJSON Text Sequences, geojsons). Default to NO. Files are given the
.json
extension if extension is not provided.
15.3.2.8. SAP HANA Spatial Layers
This section contains some details on how QGIS accesses SAP HANA layers. Most of the time, QGIS should simply provide you with a list of database tables and views that can be loaded, and it will load them on request. However, if you have trouble loading an SAP HANA table or view into QGIS, the information below may help you understand the root cause and assist in resolving the issue.
Feature Identification
If you’d like to use all of QGIS’ feature editing capabilities, QGIS must be able to unambiguously identify each feature in a layer. Internally, QGIS uses a 64-bit signed integer to identify features, whereas the negative range is reserved for special purposes.
Therefore, the SAP HANA provider requires a unique key that can be mapped to a positive 64-bit integer to fully support QGIS’ feature editing capabilities. If it is not possible to create such a mapping, you might still view the features, but editing might not work.
Adicionando tabelas
When adding a table as a layer, the SAP HANA provider uses the table’s primary key to map it to a unique feature id. Therefore, to have full feature editing support, you need to have a primary key to your table definition.
The SAP HANA provider supports multi-column primary keys, but if you’d like to
get the best performance, your primary key should be a single column of type
INTEGER
.
Adding views
When adding a view as a layer, the SAP HANA provider cannot automatically identify columns that unambiguously identify a feature. Furthermore, some views are read-only and cannot be edited.
To have full feature editing support, the view must be updatable (check column
IS_READ_ONLY
in system view SYS.VIEWS
for the view in question) and you
must manually provide QGIS with one or more columns that identify a feature. The
columns can be given by using
and then
selecting the columns in the Feature id column. For best
performance, the Feature id value should be a single INTEGER
column.
15.3.3. Layers crossing 180° longitude
Many GIS packages don’t wrap layers with a geographic reference system (lat/lon) crossing the 180 degrees longitude line. As result, if we open such a layer in QGIS, we could see two widely separated locations, that should appear near each other. In Fig. 15.31, the tiny point on the far left of the map canvas (Chatham Islands) should be within the grid, to the right of the New Zealand main islands.
15.3.3.1. Solving in PostGIS
A work-around is to transform the longitude values using PostGIS and the ST_ShiftLongitude function. This function reads every point/vertex in every component of every feature in a geometry, and shifts its longitude coordinate from -180..0° to 180..360° and vice versa if between these ranges. This function is symmetrical so the result is a 0..360° representation of a -180..180° data and a -180..180° representation of a 0..360° data.
Import data into PostGIS (Importing Data into PostgreSQL) using, for example, the DB Manager plugin.
Use the PostGIS command line interface to issue the following command:
-- In this example, "TABLE" is the actual name of your PostGIS table update TABLE set geom=ST_ShiftLongitude(geom);
If everything went well, you should receive a confirmation about the number of features that were updated. Then you’ll be able to load the map and see the difference (Figure_vector_crossing_map).