Reading KML My Tracks files in ipython
It's easy to record tracks (for instance while running) using the "My tracks" app on android systems. What about being able to re-use them?
In :doc:2014-11-22-reading-kml-my-tracks-files-in-ipython
we reviewed different approches. Let's now try to use this data.
In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
the xmltodict solution¶
In [2]:
class KmlReader():
def __init__(self, filename):
import pandas as pd
import xmltodict
with open(filename) as f:
kml_dict = xmltodict.parse(f)
doc = kml_dict['kml']['Document']
keypoint_folder = doc['Folder']
Placemark = doc['Placemark']
self.tracks_type = Placemark[1]['ExtendedData']['Data']['value']
track = Placemark[1]['gx:MultiTrack']['gx:Track']
self.lon, self.lat, self.alt = [], [], []
for when, where in zip(track['when'], track['gx:coord']):
self.whens = pd.to_datetime(track['when'])
for coord in track['gx:coord']:
lon, lat, alt = coord.split(' ')
self.lon.append(np.float(lon))
self.lat.append(np.float(lat))
self.alt.append(np.float(alt))
filename = '/tmp/test.kml'
track = KmlReader(filename)
In [3]:
import pandas as pd
whens = pd.to_datetime(track.whens)
print whens[0], whens[0].ctime()
In [4]:
df = pd.DataFrame(data = zip(track.whens, track.lon, track.lat, track.alt), columns=['time', 'lon', 'lat', 'alt'])
In [5]:
df
Out[5]:
In [6]:
df.info()
Looks good... Can we plot that?
In [7]:
df['alt'].plot(figsize=(15,5));
Another way:
In [8]:
df.plot(x='time', y='alt', figsize=(15,5), label='altitude', legend=False);
In [9]:
df.plot(x='time', y='lon', figsize=(15,5), label='longitude')
df.plot(x='time', y='lat', figsize=(15,5), label='lattitude', legend=False);
In [10]:
df.lon.plot(x='time', figsize=(15,5))
df.lat.plot(x='time', secondary_y=True, style='g');
In [11]:
df.plot(x='lon', y='lat', figsize=(15,15), legend=False);
In [12]:
plt.plot(df.lon.values, df.lat.values)
Out[12]:
embedding that info in a map¶
In [13]:
from IPython.display import IFrame
from IPython.core.display import display
# Google Maps URL template for an iframe
lat, lon, zoom = df.lat.values.mean(), df.lon.values.mean(), 14
google_maps_url = "http://maps.google.com/maps?q={0}+{1}&" + \
"ie=UTF8&t=h&z={2}&{0},{1}&output=embed".format(lat, lon, zoom)
display(IFrame(google_maps_url, '425px', '350px'))
In [14]:
!pip install smopy
In [15]:
import smopy
print df.lat.values.min(), df.lon.values.min(), df.lat.values.max(), df.lon.values.max()
map = smopy.Map((df.lat.values.min(), df.lon.values.min(), df.lat.values.max(), df.lon.values.max()), z=13)
map.show_ipython()
In [16]:
ax = map.show_mpl()
In [ ]:
!pip install git+https://github.com/rossant/smopy.git
to determine the zoopm, use http://wiki.openstreetmap.org/wiki/Zoom_levels
In [ ]:
x, y = map.to_pixels(48.86151, 2.33474)
ax = map.show_mpl(figsize=(8, 6))
ax.plot(x, y, 'or', ms=10, mew=2);