Converting a shapefile to KML or GeoJSON
In this recipe, we'll convert a layer to KML and GeoJSON. Google KML is an Open GIS Consortium 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
:
https://github.com/GeospatialPython/Learn/raw/master/hancock.zip
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 a KML file:
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")
Make sure that the layer is loaded correctly:
vectorLyr.isValid()
Next, use the file writer to save it as a KML file by specifying the file type as KML:
QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, ...