In [1]:
import geopandas as gpd
import folium
import matplotlib.pyplot as plt
We make use of nybb dataset
In [2]:
path = gpd.datasets.get_path('nybb')
df = gpd.read_file(path)
df.head()
Out[2]:
Plot from the original dataset
In [3]:
df.plot(figsize=(6, 6))
plt.show()
One thing to notice is that the values of the geometry do not directly represent the values of latitude of longitude in geographic coordinate system
In [4]:
print(df.crs)
As folium(i.e. leaflet.js) by default takes input of values of latitude and longitude, we need to project the geometry first
In [5]:
df = df.to_crs(epsg=4326)
print(df.crs)
df.head()
Out[5]:
In [6]:
df.plot(figsize=(6, 6))
plt.show()
Initialize folium map object
In [7]:
m = folium.Map(location=[40.70, -73.94], zoom_start=10, tiles='CartoDB positron')
m
Out[7]:
Overlay the boundaries of boroughs on map with borough name as popup
In [8]:
for _, r in df.iterrows():
#without simplifying the representation of each borough, the map might not be displayed
#sim_geo = gpd.GeoSeries(r['geometry'])
sim_geo = gpd.GeoSeries(r['geometry']).simplify(tolerance=0.001)
geo_j = sim_geo.to_json()
geo_j = folium.GeoJson(data=geo_j,
style_function=lambda x: {'fillColor': 'orange'})
folium.Popup(r['BoroName']).add_to(geo_j)
geo_j.add_to(m)
m
Out[8]:
Add marker showing the area and length of each borough
In [9]:
df['lat'] = df.centroid.y
df['lon'] = df.centroid.x
df.head()
Out[9]:
In [10]:
for _, r in df.iterrows():
folium.Marker(location=[r['lat'], r['lon']], popup='length: {} <br> area: {}'.format(r['Shape_Leng'], r['Shape_Area'])).add_to(m)
m
Out[10]: