Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

https://geospatialpython.googlecode.com/files/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 KML:

  1. Start QGIS.

  2. From the Plugins menu, select Python Console.

  3. First load the layer and validate it:

    vectorLyr =  QgsVectorLayer('/qgis_data/hancock/hancock.shp', 'Hancock' , "ogr")
    vectorLyr.isValid()
    
  4. Then, establish the destination CRS. KML should always be in EPS:4326:

    dest_crs = QgsCoordinateReferenceSystem(4326)
    
  5. 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...