I have a shapefile with polygons and want to add an attribute field with the WKT in QGIS 3.4.
The function geom_to_wkt
in the Field Calculator isn't working and I don't know how to do it. Any ideas?
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityI have a shapefile with polygons and want to add an attribute field with the WKT in QGIS 3.4.
The function geom_to_wkt
in the Field Calculator isn't working and I don't know how to do it. Any ideas?
You need to both (i) create a new string attribute with a high character limit and (ii) use the field calculator to convert the geometry to its WKT representation.
Use the field calculator as shown in the screenshots below to do this (select what is here "Neues Feld anlegen" instead of "Vorhandenes Feld erneuern" to create a new attribute for the results of the calculation):
The field will hold the geometry as seen in the preview above:
With Python/PyQGIS, the same approach would look as follows:
params = {
'INPUT' : <input layer / file path for input layer>,
'FIELD_NAME' : "WKT",
'FIELD_TYPE' : 2, # String
'FIELD_LENGTH' : 100, # String character limit
'NEW_FIELD' : 1, # 1 = new field, 0 = existing field
'FORMULA' : 'geom_to_wkt( $geometry )', # formula
'OUTPUT' : <file path for output layer>
}
processing.run('qgis:fieldcalculator', params)
I can suggest using a "Virtual Layer" through Layer > Add Layer > Add/Edit Virtual Layer...
Let's assume there is a polygon layer 'districts'
with its attribute table accordingly, see image below.
With the following Query by means of QGIS native geometry function geom_to_wkt()
, it is possible to achieve the result
SELECT *, geom_to_wkt(geometry) AS wkt
FROM "districts"
The output Virtual Layer will maintain original geometry and all initial attributes including a new, namely 'wkt'.
The alternative query will contain ST_AsText()
parameter.
It returns the Well-Known Text representation of the geometry/geography. Optional argument may be used to reduce the maximum number of decimal digits after floating-point used in the output (defaults to 15).
SELECT *, ST_AsText(geometry) AS wkt
FROM "districts"
geom_to_wkt( $geometry )
? – J. Monticolo Sep 25 '19 at 12:11