I am using PyQGIS 3.
I pull in a line table from postgres database. and one of the attributes is a point geometry, when I open the attribute table that column shows data in this format:
SRID=4326;POINT(-101.82683089226423 31.232703471526868)
and printing out this attribute for each feature prints this out as a string. Printing out the type name and type I get this:
TypeName:geometry, Type:10
How do I deal with this in my python code?
Do I have to treat it like a string and split the text to get the "POINT(-101.82683089226423 31.232703471526868)
" or is there a way to treat this as a point geometry so that I can do QgsGeometry
things with it?
I tried this:
print(QgsGeometry.fromWkt(feature['label_location']))
and I got this:
<QgsGeometry: null>
How do I cast this to a QgsGeometry
?
This works:
QgsGeometry.fromWkt(feature['label_location'].split(';')[-1])
but seems kind of crude.
Is there a better way?
I tried to use the above method to update the attribute, but I could not update it in a way that maintains the format. I have another place in my code that expects this specific string format and in the postgres table it is wkb. I would like to avoid running a query to do this and would ideally find a way to use all QGIS functions but it may not be possible.
-
I dont think it is crude. it is easy to understand and worksBera– Bera2022年07月26日 08:21:39 +00:00Commented Jul 26, 2022 at 8:21
-
@BERA but it does not work if I want to update this attribute in a way that reflects back on the database properly, and also looks the same as the others, not that I know of anyways. It seems to me it would be cleaner to understand what type this is so that it can be cast to geometry like other geometry types. I'm not sure why qgis displays geometries this way.tbob– tbob2022年07月26日 12:51:55 +00:00Commented Jul 26, 2022 at 12:51
-
Can you show us the code?Diogo Barros– Diogo Barros2023年05月17日 09:01:19 +00:00Commented May 17, 2023 at 9:01
2 Answers 2
This format is known as EWKT (Extended Well-Known text, see https://postgis.net/docs/ST_GeomFromEWKT.html) and currently not supported in QGIS except for certain PostGIS contexts.
You can see their implementation at https://github.com/qgis/QGIS/blob/46a2458cdf50364442b009cbb3fcee61eccdd835/src/providers/postgres/qgspostgresprovider.cpp#L417 and borrow the regular expression if you prefer it to the split()
approach. I think your approach is pretty much perfect.
This might make a great feature request in QGIS. See https://lists.osgeo.org/pipermail/qgis-developer/2022-January/064394.html for some existing discussion around it.
You use the geometry()
method of the feature
to get the point (or line, or polygon).
for f in features:
geom = f.geometry()
-
1This is a line layer and will give me the line geometry, I'm trying to get the geometry from the 'label_locaiton' attribute which is a point geometry.tbob– tbob2022年07月25日 16:49:12 +00:00Commented Jul 25, 2022 at 16:49