In [1]:
import os
import folium
print(folium.__version__)
GeoPandas is a project to add support for geographic data to pandas objects. (See https://github.com/geopandas/geopandas)
It provides (among other cool things) a GeoDataFrame
object that represents a Feature collection.
When you have one, you may be willing to use it on a folium map. Here's the simplest way to do so.
In this example, we'll use the same file as GeoPandas demo ; it's containing the boroughs of New York City.
In [2]:
import geopandas
nybb = os.path.join('data', 'nybb.shp')
boros = geopandas.GeoDataFrame.from_file(nybb)
boros
Out[2]:
To create a map with these features, simply put them in a GeoJson
:
In [3]:
m = folium.Map([40.7, -74], zoom_start=10, tiles='cartodbpositron')
folium.GeoJson(boros).add_to(m)
m.save(os.path.join('results', 'geopandas_0.html'))
m
Out[3]:
Quite easy.
Well, you can also take advantage of your GeoDataFrame
structure to set the style of the data. For this, just create a column style
containing each feature's style in a dictionnary.
In [4]:
boros['style'] = [
{'fillColor': '#ff0000', 'weight': 2, 'color': 'black'},
{'fillColor': '#00ff00', 'weight': 2, 'color': 'black'},
{'fillColor': '#0000ff', 'weight': 2, 'color': 'black'},
{'fillColor': '#ffff00', 'weight': 2, 'color': 'black'},
{'fillColor': '#00ffff', 'weight': 2, 'color': 'black'},
]
boros
Out[4]:
In [5]:
m = folium.Map([40.7, -74], zoom_start=10, tiles='cartodbpositron')
folium.GeoJson(boros).add_to(m)
m.save(os.path.join('results', 'geopandas_1.html'))
m
Out[5]:
Folium should work with any object that implements the __geo_interface__
but be aware that sometimes you may need to convert your data to epsg='4326'
before sending it to folium
.
In [6]:
import fiona
import shapely
fname = os.path.join('data', '2014_08_05_farol.gpx')
with fiona.open(fname, 'r', layer='tracks') as records:
tracks = [
shapely.geometry.shape(record['geometry']) for record in records
]
track = tracks[0]
m = folium.Map(tiles='cartodbpositron')
folium.GeoJson(track).add_to(m)
m.fit_bounds(m.get_bounds())
m.save(os.path.join('results', 'geopandas_2.html'))
m
Out[6]: