Yesterday I shared how I plotted locations of videos shot with my Sony FDR-X3000 camera on a map. I was already pretty happy. Then I got a tip from Twitter user Bob Haffner (@bobhaffner): why not use Folium to create my maps?
Huh? I already got a working map now, didn’t I? Well creating a map with matplotlib is a bit of a hassle. You’ve got to download a base map from Openstreetmap.org. And if it’s too big, like the map of all my rides in the Vercors and DrĂ´me (France) last year, you might not get it.
Folium
A quick look at blogs about Folium tell me you don’t need to download a map. It even does zoomable maps. Okay. Wasn’t exactly looking for that. But sounds great.
And I do like the markers you can create. Even with popup texts. Yes please!
Changing the code
Of course, the new version of this code is on Github in my repo: https://github.com/Marcel-Jan/media_gpsplot.
First of all we need to import Folium:
import folium
So I already have my dataframe with geo data. Don’t need to change that. But I’m going to change all the plotting stuff.
For Matplotlib we needed to define a boundary box. For Folium we only have to have the center point of the map. And you don’t need to load map images or anything here. So that is very nice.
# Find center of folium map latitude_mean = geodf['latitude'].mean() longitude_mean = geodf['longitude'].mean()
Now I define a map:
my_map = folium.Map(location=[latitude_mean, longitude_mean], zoom_start=12)
And for each point in my Pandas dataframe I want a marker. Folium markers allow you to add popup text, which you can make nice with HTML tags. I decided I wanted to have my filename and creation date in here.
for index, georow in geodf.iterrows(): folium.Marker([georow['latitude'], georow['longitude']], popup=f"filename: {georow['xmlfilename']}</br>creationdate: {georow['creationdate']}").add_to(my_map)
Showing the map
But why didn’t PyCharm show my map? Well, it turns out that Folium is more notebook (Jupyter) oriented. Not to worry. You can save the html:
my_map.save('videogps_folium.html')
And when you open this file, there you have it: a wonderful, zoomable map with markers for all my video locations.
And it turns out that now the map is zoomable, this is actually very useful. Remember last blogpost that I would probably create my maps per day? Not anymore. I will just zoom in to that particular ride now.
As mentioned, you can find my new version of this code in my Github repo:
https://github.com/Marcel-Jan/media_gpsplot
You can also find an example output file:
https://github.com/Marcel-Jan/media_gpsplot/blob/main/videogps_folium.html
Other blogposts I wrote about geo data in Python:
Adding the track of my bike ride in Folium (Antpaths and Polylines)