4

I try to get features geometry from a polygon layer. I will insert this geometry into one of my postgis table so I think it would be easier if I export the geometry into WKB format. But sadly I just recognise that QgsGeometry doesn't support function to export geometry into wkb format (it's just for wkt and geojson).

enter image description here

Here is my script, but it's using exportToWkt function:

from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt4.QtGui import QAction, QIcon
from qgis.core import QgsMapLayer
from qgis.core import QgsFeature, QgsGeometry
selectedLayer =iface.mapCanvas().layers()[0]
for feature in selectedLayer.getFeatures():
    geom = feature.geometry()
    print geom.exportToWkt()

Any ideas to export this geometry into wkb format ?

  • 1
    Did you look to see how the DB manager does it? That's the joy of open source – Ian Turton Feb 8 '17 at 18:22
3

See .asWkb() in PyQGIS - Converting WKB to String, and others...

selectedLayer =iface.mapCanvas().layers()[0]
# First feature
elem = selectedLayer.getFeatures().next()
geom= elem.geometry()
print geom.asPoint()
(205553,89857.7)

Now, export into wkb format

wkb = geom.asWkb()

Import to ogr geometry

from osgeo import ogr
geom_ogr = ogr.CreateGeometryFromWkb(wkb)
print geom_ogr.GetX(),geom_ogr.GetY(),geom_ogr.GetZ()
205552.628666 89857.6693284 222.199996948

Import to Shapely geometry

from shapely.wkb import loads
point = loads(wkb)
print point.wkt 
POINT Z (205552.628666262 89857.66932836606 222.1999969482422)

Import to PostGIS geometry, look at Importación en PostGIS de capas vectoriales mediante psycopg2 en ambiente de PyQGIS (in Spanish but the scripts are universals)

In the José Guerrero script

...
ls = wkb.encode('hex')
# Send it to PostGIS
cur.execute('CREATE TABLE my_points(geom geometry, name text)')
cur.execute(
   'INSERT INTO my_points(geom, name)'
   'VALUES (ST_SetSRID(%(geom)s::geometry, %(srid)s), %(name)s)',
    {'geom': ls, 'srid': 32612, 'name': 'First point'})
...
| improve this answer | |
  • 2
    I've tried to use this asWkb() as the solution, but sadly when I try to import it to postgis table it will return error because of the SRID that doesn't match. This solution will return geometry in wkb format and default SRID as 0. How can I change the SRID ? @gene – septin Feb 9 '17 at 23:28
  • @septin, did you manage to set the SRID? – adamczi Feb 16 '18 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.