Generating dynamic Google maps with Python1/02/2009
As I have mentioned before, I have been putting together some dynamically generated maps for environmental information. 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 while 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.
http://maps.google.co.nz/maps?q=http://gis.someserver.com/dynamicmap.py Just copy the address, send it to some one and, presto, they have access to my map. However, I wanted to embed it in a blog post§ and I was struggling to do it. The solution was to click on the ‘Link’ link in the generated map to copy the ‘Paste HTML to embed in website’ link. This gives an
iframe block that can be copied in any page or blog post.
It was not too bad for mucking around on Friday in between doing house chores.Filed in geocoded, programming, web