I originally wrote this code on 2 February 2009, as a quick hack to publish air pollution in Santiago. The air quality stations now present data in a different way, so the mapping doesn’t work, but the general idea is still useful. A barebones version of my Python code to generate the KML file is:
#!/usr/bin/env python # encoding: utf-8 import urllib, random # Charting function def lineChart(data, size = '250x100'): baseURL = 'http://chart.apis.google.com/chart?cht=lc&chs=' baseData = '&chd=t:' newData = ','.join(data) baseData = baseData + newData URL = baseURL + size + baseData return URL # Reading test data: connecting to server and extracting lines f = urllib.urlopen('http://gis.someserver.com/TestData.csv') stations = f.readlines() kmlBody = ('') for s in stations: data = s.split(',') # Generate random data a =  for r in range(60): a.append(str(round(random.gauss(50,10), 1))) chart = lineChart(a) # data is csv as station name (0), long (1), lat (2), y (3) kml = ( '<Placemark>\n' '<name>%s</name>\n' '<description>\n' '<![CDATA[\n' '<p>Value: %s</p>\n' '<p><img src="%s" width="250" height="100" /></p>\n' ']]>\n' '</description>\n' '<Point>\n' '<coordinates>%f,%f</coordinates>\n' '</Point>\n' '</Placemark>\n' ) %(data, data, chart, float(data), float(data)) kmlBody = kmlBody + kml # Bits and pieces of the KML file contentType = ('Content-Type: application/vnd.google-earth.kml+xml\n') kmlHeader = ('<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n' '<kml xmlns=\"http://earth.google.com/kml/2.1\">\n' '<Document>\n') kmlFooter = ('</Document>\n' '</kml>\n') print contentType print kmlHeader print kmlBody print kmlFooter
description tag. That was the time when I remembered playing with Google Charts a long time ago. The
lineChart function above is simply a call to create a line chart using the charts API. Because this is a test, I used 60 randomly generated data points, which explains the presence of
random as an imported library. The actual code is even larger, because I was (and am) also doing data scrapping from the Chilean meteorological service web pages.
iframe block that can be copied in any page or blog post, like so:
It was not too bad for mucking around on a Friday in between doing house chores.