import os
import folium
print(folium.__version__)
0.3.0+162.g0540622.dirty
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.
import geopandas
nybb = os.path.join('data', 'nybb.shp')
boros = geopandas.GeoDataFrame.from_file(nybb)
boros
BoroCode | BoroName | Shape_Area | Shape_Leng | geometry | |
---|---|---|---|---|---|
0 | 5 | Staten Island | 1.623847e+09 | 330454.175933 | (POLYGON ((970217.0223999023 145643.3322143555... |
1 | 3 | Brooklyn | 1.937810e+09 | 741227.337073 | (POLYGON ((1021176.479003906 151374.7969970703... |
2 | 4 | Queens | 3.045079e+09 | 896875.396449 | (POLYGON ((1029606.076599121 156073.8142089844... |
3 | 1 | Manhattan | 6.364308e+08 | 358400.912836 | (POLYGON ((981219.0557861328 188655.3157958984... |
4 | 2 | Bronx | 1.186822e+09 | 464475.145651 | (POLYGON ((1012821.805786133 229228.2645874023... |
To create a map with these features, simply put them in a GeoJson
:
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
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.
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
BoroCode | BoroName | Shape_Area | Shape_Leng | geometry | style | |
---|---|---|---|---|---|---|
0 | 5 | Staten Island | 1.623847e+09 | 330454.175933 | (POLYGON ((970217.0223999023 145643.3322143555... | {u'color': u'black', u'fillColor': u'#ff0000',... |
1 | 3 | Brooklyn | 1.937810e+09 | 741227.337073 | (POLYGON ((1021176.479003906 151374.7969970703... | {u'color': u'black', u'fillColor': u'#00ff00',... |
2 | 4 | Queens | 3.045079e+09 | 896875.396449 | (POLYGON ((1029606.076599121 156073.8142089844... | {u'color': u'black', u'fillColor': u'#0000ff',... |
3 | 1 | Manhattan | 6.364308e+08 | 358400.912836 | (POLYGON ((981219.0557861328 188655.3157958984... | {u'color': u'black', u'fillColor': u'#ffff00',... |
4 | 2 | Bronx | 1.186822e+09 | 464475.145651 | (POLYGON ((1012821.805786133 229228.2645874023... | {u'color': u'black', u'fillColor': u'#00ffff',... |
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