In this recipe, we'll convert a layer to KML. KML is an Open Geospatial Consortium (OGC) standard and is supported by the underlying OGR library used by QGIS.
For this recipe, download the following zipped shapefile and extract it to a directory named /qgis_data/hancock
:
To convert a shapefile to the KML XML format, we'll load the layer and then use the QgsVectorFileWriter
object to save it as KML:
vectorLyr = QgsVectorLayer('/qgis_data/hancock/hancock.shp', 'Hancock' , "ogr") vectorLyr.isValid()
dest_crs = QgsCoordinateReferenceSystem(4326)
QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, "/qgis_data/hancock/hancock.kml", "utf-8", dest_crs, "KML")
You will end up with a KML file in the directory next to your shapefile. KML supports styling information. QGIS uses some default styling information that you can change, either by hand using a text editor, or programmatically using an XML library such as Python's ElementTree. KML is one of many standard vector formats you can export using this method.