Skip to content

Instantly share code, notes, and snippets.

@axiomsofchoice
Created March 28, 2011 11:35
Show Gist options
  • Save axiomsofchoice/890319 to your computer and use it in GitHub Desktop.
Save axiomsofchoice/890319 to your computer and use it in GitHub Desktop.
"""Outputs a KML file with locations of certain comments from patientopinion.org.uk
Requires an API key to be provided on the command-line
"""
import urllib2
import re, sys
from xml.etree.ElementTree import *
# TODO: implement a paging mechanism
takeNumber = 20
req = urllib2.Request(url='http://www.patientopinion.org.uk/api/rest.svc/v1/postings/search?tag=dirty&take=%s&apikey=%s'
% (takeNumber,sys.argv[1]))
f = urllib2.urlopen(req)
xmltree = ElementTree()
xmltree.parse(f)
if xmltree is None:
print >> sys.stderr, "Could not connect to patientopinion.org.uk"
exit(-1)
print """<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<!-- Built as part of http://www.iip-symposium.info/ hackday
Compiled from Open Data available at http://www.patientopinion.org.uk/info/api-docs and http://www.uk-postcodes.com/api.php -->
<Document>
"""
idnum = 0
# Iterate over all the Opions returned
treeroot = xmltree.getroot()
for ops in treeroot.findall('{http://www.patientopinion.org.uk/api/rest/v1}Opinion'):
# Get the various fields from the element
pstc = ops.find('{http://www.patientopinion.org.uk/api/rest/v1}HealthServices/{http://www.patientopinion.org.uk/api/rest/v1}HealthService/{http://www.patientopinion.org.uk/api/rest/v1}Postcode')
if pstc is None:
continue
locname = ops.find('{http://www.patientopinion.org.uk/api/rest/v1}HealthServices/{http://www.patientopinion.org.uk/api/rest/v1}HealthService/{http://www.patientopinion.org.uk/api/rest/v1}Name')
locdesc = ops.find('{http://www.patientopinion.org.uk/api/rest/v1}Body')
# Next look up the postcode using a different web service to get lat/long co-ordinates
lookupURL = 'http://www.uk-postcodes.com/postcode/'+re.sub(r'\s','',pstc.text)+'.xml'
postcodeLookupReq = urllib2.Request(url=lookupURL)
pcf = urllib2.urlopen(postcodeLookupReq)
tree = ElementTree()
tree.parse(pcf)
rootelem = tree.getroot()
lat = rootelem.find('geo/lat')
lng = rootelem.find('geo/lng')
print """ <Placemark id=\"%s\">
<name>%s</name>
<description>%s</description>
<Point>
<coordinates>%s,%s,0</coordinates>
</Point>
</Placemark>""" % (idnum,re.sub(r'\s','-',locname.text),"desc",lng.text,lat.text)
idnum += 1
print """
</Document>
</kml>"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment