Skip to content

Instantly share code, notes, and snippets.

@ZengetsuFR
Last active August 29, 2015 14:08
Show Gist options
  • Save ZengetsuFR/5dcb9db3c540ba2d0dda to your computer and use it in GitHub Desktop.
Save ZengetsuFR/5dcb9db3c540ba2d0dda to your computer and use it in GitHub Desktop.
playing with chicago's public data
# -*- coding: utf-8 -*-
#exercise from "Learn Python Through Public Data Hacking" see youtube here : http://youtu.be/RrPZza_vZ3w
#Travis traveled to Chicago and took the Clark Street #22 bus up to Dave's office.
#Problem: He just left his suitcase on the bus!
#Your task: Get it back!
#Dave's office is located at:
# latitude =41.980262
# longitude =-87.668452
#this program monitors the identified buses and
#reports their current distance from Dave's office.
#When the bus gets closer than 0.5 miles,
#have the program issue an alert by openning a web-page showing the bus location on a map.
#Travis will meet the bus and get his suitcase.
from xml.etree.ElementTree import parse
import webbrowser, math, urllib,os,time,console
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
import cgi
import csv
TEMPLATE = ('<!DOCTYPE html><html><head></head>' +
'<body style="margin:20px; font-family:sans-serif; background:#ddd">' +
"<h2>Afficher la position dynamique d'un bus (chicago) et une position fixe</h2>" +
'<form action="/" method="POST" enctype="multipart/form-data">' +
'<strong> Location: </strong>' +
'<input type="text" name="center" value="{{CENTER}}"></input>' +
'<strong> &nbsp; &nbsp; Zoom: </strong>' +
'<select name="zoom" style="width:50px" onchange="form.submit()">' +
'<option>0<option>1<option>2<option>3<option selected>4' +
'<option>5<option>6<option>7<option>8<option>9</select>' +
'&nbsp; &nbsp; <input type="submit" value="Get Map">' +
'</form><br/><br/>{{MAP}}</body></html>')
class bus():
def __init__(self,busid,buslatitude,buslongitude):
self.id = busid
self.latitude = buslatitude
self.longitude = buslongitude
#Save XML data about the Clark Street #22 bus
def saveXML():
u = urllib.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22')
data = u.read()
f = open('rt22.xml','wb')
f.write(data)
f.close
console.hud_alert('close data OK')
time.sleep(2)
def getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2):
'''permet de calculer la distance entre deux points'''
R = 6371 #Radius of the earth in km
dLat = deg2rad(lat2-lat1)
dLon = deg2rad(lon2-lon1)
a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(deg2rad(lat1)) * math.cos(deg2rad(lat2)) * math.sin(dLon/2) * math.sin(dLon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = R * c #Distance en km
miles = d * .6214 #convertir km en miles
return d
def deg2rad(deg):
return deg * (math.pi/180)
#return approximate range in miles between 2 latitudes
def distance_approximative(latitude1,latitude2):
return 69*abs(latitude1-latitude2)
def monitor():
global office_position
global bus_position
global bFindbus
global travisBus
console.hud_alert('chercher XML')
saveXML()
doc = parse('rt22.xml')
console.hud_alert('SaveXML OK')
office_latitude= 41.980262
office_longitude= -87.668452
office_position =str(office_latitude)+","+str(office_longitude)
bFindbus = False
#look into xml
#find latitude and longitude for every node
#compare distance from travis's office
for bus in doc.findall('bus'):
idbus = bus.findtext('id')
bus_latitude = float(bus.findtext('lat'))
bus_longitude = float(bus.findtext('lon'))
direction = bus.findtext('d')
console.hud_alert(direction)
if direction.startswith('North'):
distance = getDistanceFromLatLonInKm(office_latitude,office_longitude,bus_latitude,bus_longitude)
distance_approx = distance_approximative(office_latitude,bus_latitude)
console.hud_alert(str(distance_approx))
if distance_approx <= 0.5:
bFindbus = True
print('to North')
print('distance : ' + str(distance))
print('distance approximative : ' + str(distance_approx))
print('bus num :' + idbus + ' direction : '+ direction)
print('latitude : ' + str(bus_latitude) + ' long : ' + str(bus_longitude) +'\n')
bus_position = str(bus_latitude)+","+str(bus_longitude)
break
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self): #load initial page
html = TEMPLATE.replace('{{CENTER}}', '')
m = ('<img src="http://maps.googleapis.com/maps/api/staticmap?center='+office_position+'&zoom=14' + '&size=500x400&sensor=false&markers=color:red%7Clabel:O%7C'+office_position +'&markers=color:blue%7Clabel:B%7C'+ bus_position + '">')
html = html.replace('{{MAP}}',m)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(html)
def do_POST(self): #process requests
form = cgi.FieldStorage(fp = self.rfile, headers = self.headers,environ = {'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type']})
c = office_position #form.getvalue('center')
#t = form.getvalue('type')
z = form.getvalue('zoom')
#s = form.getvalue('size')
m = ('<img src="http://maps.googleapis.com/maps/api/staticmap?center='+office_position+'&zoom=1' + z + '&size=500x400&sensor=false&markers=color:red%7Clabel:O%7C'+office_position +'&markers=color:blue%7Clabel:B%7C'+ bus_position + '">')
html = TEMPLATE.replace('{{CENTER}}', c)
html = html.replace('>' + z, ' selected>' + z)
html = html.replace('{{MAP}}', m)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(html)
monitor()
if bFindbus==True :
server = HTTPServer(('', 80), RequestHandler)
webbrowser.open('http://localhost', stop_when_done = True)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment