views:

128

answers:

4

Are there any open source libraries (preferably python) that will convert a kml file to an image file?

I have an open source web-based application that allows users to draw shapes on a Google Earth Map, and I would like to provide them with a pdf that contains their map with the shapes that they have drawn.

Right now the users are provided instructions for using either Print Screen or exporting the kml, but the former seems a little lame and the latter doesn't give them an image unless they have access to other software.

Is this a pipe dream?

A: 

It's not really a question of "convert"; KML's can hold all sorts of things - polygons, icons, links, info, etc.

However, KML is XML, so there's no reason why you couldn't parse the KML file with something like expat or etree to extract the polygon definitions. From there you could (for example) draw them on a PDF.

Seth
+1  A: 

See http://mapnik.org/faq/, it supports OGR formats (KML is one of them). Mapnik has python bindings and is easy to use.

Cairo renderer supports PDF and SVG, you just need to set everything up correctly.

alxx
A: 

Have a look at this post "Interactive mapping with HTML5, JavaScript, and Canvas". It is about rendering KML with the HTML5 canvas element.

Hope it helps.

http://indiemaps.com/blog/2010/06/interactive-mapping-with-html5-javascript-and-canvas/

André Ricardo
A: 

I recently did something like this with Mapnik. After installing Mapnik with all optional packages, this Python script can export a path from a KML file to a PDF or bitmap graphic:

#!/usr/bin/env python

import mapnik
import cairo

m = mapnik.Map(15000, 15000, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs") # end result: OpenStreetMap projection
m.background = mapnik.Color(0, 0, 0, 0)

bbox = mapnik.Envelope(-10000000, 2000000, -4000000, -19000000) # must be adjusted
m.zoom_to_box(bbox)

s = mapnik.Style()
r = mapnik.Rule()

polygonSymbolizer = mapnik.PolygonSymbolizer()
polygonSymbolizer.fill_opacity = 0.0
r.symbols.append(polygonSymbolizer)

lineSymbolizer = mapnik.LineSymbolizer(mapnik.Color('red'), 1.0)
r.symbols.append(lineSymbolizer)

s.rules.append(r)
m.append_style('My Style',s)

lyr = mapnik.Layer('path', '+init=epsg:4326')
lyr.datasource = mapnik.Ogr(file = './path.kml', layer = 'path')
lyr.styles.append('My Style')
m.layers.append(lyr)

# mapnik.render_to_file(m,'./path.png', 'png')

file = open('./path.pdf', 'wb')
surface = cairo.PDFSurface(file.name, m.width, m.height)
mapnik.render(m, surface)
surface.finish()
Ole Begemann