Cloud services have become common and geospatial maps are no exception. This recipe uses a service named geojson.io, which serves vector layers online, which you can upload from QGIS using Python.
For this recipe, you will need to install the qgisio plugin using the QGIS Plugin Manager.
You will also need a shapefile in a geodetic coordinate system (WGS84) from https://geospatialpython.googlecode.com/svn/union.zip.
Decompress the ZIP file and place it in your qgis_data
directory named shapes
.
We will convert our shapefile to GeoJSON using a temporary file. We'll then use Python to call the qgisio plugin in order to upload the data to be displayed online. To do this, we need to perform the following steps:
from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * from tempfile import mkstemp import os from qgisio import geojsonio
layer = QgsVectorLayer("/qgis_data/shapes/building.shp", "Building", "ogr") name = layer.name()
handle, tmpfile = mkstemp(suffix='.geojson') os.close(handle)
crs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.PostgisCrsId)
error = QgsVectorFileWriter.writeAsVectorFormat(layer, tmpfile, "utf-8", crs, "GeoJSON", onlySelected=False)
if error != QgsVectorFileWriter.NoError: print "Unable to write geoJSON!"
with open(str(tmpfile), 'r') as f: contents = f.read()
os.remove(tmpfile)
qgisio
module:url = geojsonio._create_gist(contents, "Layer exported from QGIS", name + ".geojson")
QDesktopServices.openUrl(QUrl(url))
This recipe actually uses two cloud services. The GeoJSON data is stored on a https://github.com service named Gist that allows you to store code snippets such as JSON
. The geojson.io service can read data from Gist.
This screenshot shows the building layer on an OSM map on geojson.io, with the GeoJSON displayed next to the map:
There are additional advanced services that can serve QGIS maps, including www.QGISCloud.com and www.CartoDB.com, which can also display raster maps. Both of these services have free options and QGIS plugins. However, they are far more difficult to script from Python if you are trying to automate publishing maps to the Web as part of a workflow.