Converting a shapefile to KML
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.
Getting ready
For this recipe, download the following zipped shapefile and extract it to a directory named /qgis_data/hancock
:
How to do it...
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:
Start QGIS.
From the Plugins menu, select Python Console.
First load the layer and validate it:
vectorLyr = QgsVectorLayer('/qgis_data/hancock/hancock.shp', 'Hancock' , "ogr") vectorLyr.isValid()
Then, establish the destination CRS. KML should always be in EPS:4326:
dest_crs = QgsCoordinateReferenceSystem(4326)
Next, use the file writer to save it as a KML file by specifying the file type as KML:
QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, "/qgis_data/hancock/hancock.kml", "utf...