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-8", dest_crs, "KML")
    

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset