Skip to content

Instantly share code, notes, and snippets.

@gka
Created July 17, 2012 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gka/3129356 to your computer and use it in GitHub Desktop.
Save gka/3129356 to your computer and use it in GitHub Desktop.
Kartograph config generator for QGis

You can use this script to generate Kartograph configurations from the QGis Python console based on your current project. At the moment this works only for vector layers created from ESRI shapefiles.

  1. Copy and paste the script into the console
  2. Type qgis2kartograph('map.json') to generate the configuration
# Very first draft of a Kartograph config generator for QGis
from qgis.core import *
import json
def hexcol(c):
return '#%02x%02x%02x' % (c.red(), c.green(), c.blue())
def get_attrs_from_symbol(symbol):
attrs = {}
if isinstance(symbol, QgsLineSymbolV2):
attrs['fill'] = 'none'
attrs['stroke'] = hexcol(symbol.color())
attrs['stroke-width'] = symbol.width() * 2
elif isinstance(symbol, QgsFillSymbolV2):
attrs['fill'] = hexcol(symbol.color())
attrs['stroke'] = 'none'
if symbol.alpha() < 1.0:
attrs['opacity'] = symbol.alpha()
return attrs
def qgis2kartograph(filename):
out = []
layers = qgis.utils.iface.mapCanvas().layers()
for layer in layers:
l = dict(id=str(layer.name()))
l['src'] = unicode(layer.publicSource())
l['styles'] = {}
renderer = layer.rendererV2()
if isinstance(renderer, QgsSingleSymbolRendererV2):
l['styles']['single'] = get_attrs_from_symbol(renderer.symbol())
elif isinstance(renderer, QgsCategorizedSymbolRendererV2):
l['styles']['categorized'] = dict(column=str(renderer.classAttribute()), attrs={})
for cat in renderer.categories():
val = str(cat.value().toString())
attrs = get_attrs_from_symbol(cat.symbol())
l['styles']['categorized']['attrs'][val] = attrs
out.append(l)
out.reverse()
cfg = dict(layers=out)
open(filename, 'w').write(json.dumps(cfg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment