2

I am aware that it is possible, in QGIS, to save your Vector Layer as a KML manually, however, I want to know if there is anyway I can do this programmatically from an external Python Script that I run from PyScripter.

I am aware ArcPy has that functionality, however, I am looking for a PyQGIS Solution.

Here is how I can do it with ArcPy using the Conversion Tool Set Layer to KML

...
Layer = Output_Layer
Output_File =  r"C:Users\path\KMZ.kmz"

# Process: Layer To KML
arcpy.LayerToKML_conversion(Layer, Output_File, "0", "false", "DEFAULT","1024", "96", "CLAMPED_TO_GROUND")  
print "Layer to KMZ Conversion Complete"
print Output_Layer + " is now a .kmz"

or if there is a Python Library that will allow me to convert a shapefile to a KML/KMZ?

1 Answer 1

3
  • If you're running Pyscripter inside QGIS, you could try using the following script:

    from qgis.core import QgsVectorFileWriter, QgsVectorLayer
    
    data_source = r"path/to/shapefile"
    layer = QgsVectorLayer(data_source, "layer_name", "ogr")
    output_layer = r"C:/Users/path/KML"
    QgsVectorFileWriter.writeAsVectorFormat(layer, output_layer, "utf-8", None, "KML")
    
    print "Layer to KML Conversion Complete"
    print output_layer + " is now a .kml"
    

  • For outside QGIS, the following is the script I use which I run from the OSGeo4W Shell program (I don't have Pyscripter to test this):

    import os, sys, glob
    from qgis.core import *
    from qgis.gui import *
    from PyQt4.QtGui import *
    
    from os.path import expanduser
    home = expanduser("~")
    
    QgsApplication( [], False, home + "/AppData/Local/Temp" )
    
    QgsApplication.setPrefixPath("C://OSGeo4W64//apps//qgis", True)
    app = QApplication([])
    QgsApplication.initQgis()
    
    sys.path.append(home + '/.qgis2/python/plugins')
    from processing.core.Processing import Processing
    Processing.initialize()
    from processing.tools import *
    
    data_source = r"path/to/shapefile"
    layer = QgsVectorLayer(data_source, "layer_name", "ogr")
    output_layer = r"C:/Users/path/KML"
    QgsVectorFileWriter.writeAsVectorFormat(layer, output_layer, "utf-8", None, "KML")
    print "Layer to KML Conversion Complete"
    print output_layer + " is now a .kml"
    
    QgsApplication.exitQgis()
    app.exit()
    
2
  • Hi Joseph, Can you tell me please how can I select some fields from attribute fiels in the layer? thank you
    – nmokht97
    Jul 29, 2020 at 9:32
  • @Joseph - I get a 'argument 4 has unexpected type 'NoneType' error when I leave the 4th argument as None . Instead, using layer.crs() (the vector layer's QgsCoordinateReferenceSystem object) works for me in QGIS 3.8
    – grego
    Sep 18, 2020 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.