I am saving the postgres table loaded in QGIS to kml.

qgis.core.QgsVectorFileWriter.writeAsVectorFormat(aLayer, myFile, "ogr", projDest, "KML")

But the output file does not have the attributes. So if I want to convert/save the table into KML without losing attributes how can this be done using python.


KML is a XML format. In theory, you don't need ogr nor QGIS, you can use all the Python XML modules (standard ElementTree, lxml, ...) in combination with the psycopg2 module (or using the QGIS layer)

They are also many specific solutions in the Python Packages Index (Pypi):kml. The easiest to use are simplekml, keytree or pykml

This will require more work than using ogr and you may not get exactly what you want because the KML format it's not great for storing attributes as a data store (look at Perrygeo: Converting Shapefiles (and more) to KML or GDAL: KML - Keyhole Markup Language)

Another solution is to use the "Google Maps (tm) KML Export Form" of the MMQGIS plugin (look at How to use the MMQGIS plugin through the Python console?)

This tool exports features to KML with the capability to explicitly specify fields for the Name and Description that are always displayed in the current (as of this writing) default Google Maps (tm) interface.

The function is mmqgis_kml_export (in the mmqgis_library.py file)

from mmqgis.mmqgis_library import mmqgis_kml_export

But you need to understand the function to use it...

  • 3
    I have solved the issue. In writeAsVectorFormat there is option called datasourceOptions where we can change the name and the description. Datalist=['AltitudeMode=relativeToGround','NameField=id'] QgsVectorFileWriter.writeAsVectorFormat(aLayer, myFile, "ogr", crs, "KML",datasourceOptions =(Datalist)). – user99 Oct 6 '15 at 9:28
  • You should add this as an answer. – BritishSteel Oct 8 '15 at 9:22

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.