from mpl_toolkits.basemap import Basemap
from geopy.distance import great_circle
from matplotlib import colors
from pyorbital import tlefile
import matplotlib.pyplot as plt
import numpy as np
import math
import ephem

tlefile.TLE_URLS = (
	'http://celestrak.com/NORAD/elements/stations.txt',
)

iss_tle = tlefile.read('ISS (ZARYA)')

iss = ephem.readtle("ISS (ZARYA)", iss_tle.line1, iss_tle.line2)
obs = ephem.Observer()

# Marina del Rey
mdr_lat = 33.9803
mdr_lon = -118.4517

obs.lat = str(mdr_lat)
obs.long = str(mdr_lon)

# set up orthographic map projection
map = Basemap(projection='ortho', lat_0=mdr_lat, lon_0=mdr_lon, resolution='l')

# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='aqua')

# draw the edge of the map projection region (the projection limb)
map.drawmapboundary(fill_color='aqua')

# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))

# plot
passes = 30
for p in range(passes):
	coords = []
	dists = []
	tr, azr, tt, altt, ts, azs = obs.next_pass(iss)
	while tr < ts:
		obs.date = tr
		iss.compute(obs)
		iss_lat = math.degrees(iss.sublat)
		iss_lon = math.degrees(iss.sublong)
		dist = great_circle((mdr_lat, mdr_lon), (iss_lat, iss_lon)).miles
		coords.append([iss_lon, iss_lat])
		dists.append(dist)
		tr = ephem.Date(tr + 30.0 * ephem.second)
	md = min(dists)
	imd = 1 - (float(md) / 1400)
	hue = float(240) / float(360)
	clr = colors.hsv_to_rgb([hue, imd, 1])
	map.drawgreatcircle(coords[0][0], coords[0][1], coords[-1][0], coords[-1][1], linewidth=2, color=clr)
	obs.date = tr + ephem.minute

plt.title('Next '+ str(passes)+ ' ISS Passes Visible From Los Angeles')
plt.show()

