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, "/qgis_data/hancock/hancock.kml", "utf-8", None, "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 by hand using a text editor or programmatically using an XML library, such as Python's ElementTree
.
There's more...
Another commonly used format is GeoJSON. Note that GeoJSON should always be projected in WGS84 (EPSG:4326). You can find more information at https://tools.ietf.org/html/rfc7946#section-4. Like KML, it is a text format that is both human and computer readable. Instead of using XML like KML, GeoJSON uses JavaScript Object Notation syntax, which is much more terse than XML syntax with parsers built in for most programming languages including Python. To save the layer in this example as GeoJSON, it's as simple as just changing the output format:
QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, "/qgis_data/hancock/hancock.geojson", "utf-8", dest_crs, "GeoJSON")