1

I am aware that it is possible, in QGIS, to save your Vector Layer as a KML file 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
  • 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()
    

Your Answer

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