In a previous post I said I would try to build a GPX loader for GeoPandas. If you try to load a GPX file right now this is what you get.
import geopandas as gpd
fname = './data/2014_08_05_farol.gpx'
gdf = gpd.read_file(fname)
gdf
import fiona
fiona.listlayers(fname)
Let's get that track layer into fiona.
layer = fiona.open(fname, layer='tracks')
layer
The layer object has a lot of properties/methods. Some of the properties carries the underlying metadata. Here are some important ones:
layer.crs, layer.bounds
How many items we have in this object?
len(list(layer.items()))
What are these items?
geom = layer[0]
type(geom)
geom.keys()
geom['type'], geom['id'], geom['properties']
OK. It is a dictionary with more data and other dictionaries in it.
We are interested in the data stored into geometry['coordinates']
.
Instead of dumping a bunch of numbers in the screen lets create a
Shapely
object to inspect the geometry coordinates.
from shapely.geometry import shape
data = {'type': 'MultiLineString',
'coordinates': geom['geometry']['coordinates']}
shp = shape(data)
shp
Nice! A simple and quick way to extract tracks from GPX and export to Shapely. But this image makes no sense without a map ;-)
(Note that I created a new dictionary with a structure I know relates to a GeoJson before feeding it to Shapely.)
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io import shapereader
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
def make_map(projection=ccrs.PlateCarree()):
fig, ax = plt.subplots(figsize=(9, 13),
subplot_kw=dict(projection=projection))
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
return fig, ax
import cartopy.io.img_tiles as cimgt
request = cimgt.OSM()
extent = [-38.54, -38.48,
-13.02, -12.98]
fig, ax = make_map(projection=request.crs)
ax.set_extent(extent)
img = ax.add_image(request, 14)
s = ax.add_geometries(shp, ccrs.PlateCarree(),
facecolor='none',
edgecolor='crimson',
linewidth=2)
Have fun exploring your GPX files!
HTML(html)