Mapping with Folium
The folium library provides an easy way to plot data handled in python into a Leaflet.js map. When handling spatiotemporal data, it is nice to have an easy and fast way to plot then on an interactive map. Folium provides that functionality.
I gave this talk on 09/11/2017 at Python Users Berlin and it was my first talk at a meetup!
Here is another jupyter notebook with some folium investigations link
# Imports
import folium
import geopy
from geopy.geocoders import Nominatim
from geopy.distance import great_circle, vincenty
We can use geopy, to geolocate a query. We have to create a Nominatim object and pass a string to its geocode method. We get back the address and the coordinates.
geolocator = Nominatim()
born_place = geolocator.geocode("Pano Polemidia")
# make a list of lat, lon
born_lat_lon = [round(born_place.latitude, 3), round(born_place.longitude, 3)]
m = folium.Map(location=born_lat_lon, zoom_start=10)
folium.Marker((born_place.latitude, born_place.longitude), popup = "This is where I was born").add_to(m)
m
Let’s make a trip to the beach. Let’s go to Kourio, where you can find an ancient theatre, with wonderful view down to the beach.
It is also interesting, that the beach is in the United Kingdom!
beach_place = geolocator.geocode("Kourion ")
beach_lat_lon = [round(beach_place.latitude, 3), round(beach_place.longitude, 3)]
# create the map object
f = folium.Map(location=beach_lat_lon, zoom_start=12)
# make a list of [lat, lon] that describe a trip
trip_to_beach = [born_lat_lon] + [beach_lat_lon]
# plot the polyline
folium.PolyLine(trip_to_beach, color="red").add_to(f)
# Add markers to the start and end point
folium.RegularPolygonMarker(born_lat_lon, popup = "This is where I was born").add_to(f)
folium.RegularPolygonMarker(beach_lat_lon, popup = "This is United Kingdom").add_to(f)
f
How long does it take to go there approximately? We can use great_circle or vincenty methods to calculate distance. The vincenty distance is more accurate than the great_circle, since the first one assumes that the earth is an oblate spheroid, while the second one assumes that the earth is a sphere.
great_circle_distance = great_circle(trip_to_beach[0], trip_to_beach[1])
vincenty_distance = vincenty(trip_to_beach[0], trip_to_beach[1])
print "Vicentry distance: {vincenty} km, while great circle distance: {great_circle} km".format(vincenty=vincenty_distance.km, great_circle = great_circle_distance.km)
Vicentry distance: 11.1840423127 km, while great circle distance: 11.1690557589 km
Anyway, going there with a car, at an average speed of 70 km/h takes around 10 minutes. Of course you can not go there using the line shown above.
The next step could be to route the start and end point of our trip on the underlying network graph, to get a more accurate distance between the start and end point.