6

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?

Taras
  • 32,823
  • 4
  • 66
  • 137
Elena Lopez
  • 61
  • 1
  • 3

2 Answers2

8

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):

field calculator for new text field

The field will hold the geometry as seen in the preview above:

enter image description here

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)
aso
  • 73
  • 7
Riccardo
  • 2,648
  • 18
  • 31
4

Another solution implies the usage of 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.

input

With the following query it is possible to add a field with geometry in WKT format

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".

output_1

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"

output_2

Taras
  • 32,823
  • 4
  • 66
  • 137