Creating beautiful webmaps in Python

Hi and welcome to yet another Python tutorial that builds a real world application. This time we will learn to create webmaps. Webmaps are used to point out and display geographical locations on a map. For this purpose there is a full fledged external Python library called Folium. What Folium does is it takes a few lines of Python code and then with the help of “Leaflet.js” it converts it to HTML, CSS and Javascript to create beautiful webmaps that can be browsed in a web browser. Leaflet.js is a popular open source javasript library used for web mapping applications. Leaflet.js is an essential part of this process that works in the backgroud for us and displays the end results. When Folium, Leaflet.js and Python team up together, they create some awe-inspiring webmaps. Our final result will look like this.

webmap-popup.jpg

For this tutorial I have prepared a list of 100 volcanoes located in Japan. This list is stored in a CSV file that contains the names, geographical coordinates (latitudes and longitudes), elevation and the status of these volcanoes. The latitudes and longitudes will be used to point out the exact location of volcanoes on the map. I took this data from Wikipedia and converted it to CSV (comma seperated values) format.

japan-volcanoes-wikipedia.jpg

csv-file.jpg

Now we will code our Python application that displays the location of these volcanoes on a webmap.

What we are going to create

We are going to create a webmap that shows the location of each volcanoe as a marker. The color of the active volcanoes will be shown as red and inactive volcanoes will be shown as yellow on the map. When we click the marker, it will display some information about that volcanoe like name, elevation and status. Sounds exciting right? So lets get busy.

Requirements

  • Basic knowledge of Python
  • Internet connection
  • Python 3 installed on your computer
  • Folium and Pandas packages installed

If you haven’t installed the packages yet then install them through command line. Just go to cmd and enter:

pip install folium

And then

pip install pandas

All bases covered. So let’s start.

Coding our webmap application

First of all import the required libraries.

import folium
import pandas

Now let’s open our volcanoes.txt file and load it in a pandas dataframe object. Our volcanoes.txt file is actually a comma seperated values (CSV) file that contains all the information about volcanoes. To load the file in a Pandas dataframe object we use the pandas.read_csv() funtion that takes the name of file as an argument. Make sure to keep the CSV file in the same folder as the python script because we are passing a relative path to the function.

data = pandas.read_csv("volcanoes.txt")

Pandas dataframe are very powerful objects and the first choice of use for data analysis and data manipulation. Dataframes are quite similar to multidimentional arrays. They store the values in tabular form like rows and columns of a table. With data.columns method we can access the names of columns and then we can access the contents of those columns using data[“ColumnName”] syntax. Lets store all the columns in a seperate variable and convert the type of these variables to lists so that we can iterate over them later.

vname = list(data["Name"])
lat = list(data["Latitudes"])
lon = list(data["Longitudes"])
elev = list(data["Elevation"])
status = list(data["Status"])

We want to graphically display whether a particular volcanoe is active or not. Lets create a function that takes the status of a volcanoe as an argument and assigns a color to it. Active volcanoes will be displayed as red and inactive ones will be displayed as yellow.

def color_producer(stt):
    if stt == "Active":
        return 'red'
    else:
        return 'yellow'

Now its time to create a map object using folium.Map() method. Creating a folium.Map() object is generally the starting point of creating a webmap in Folium. It displays the Geographical area you want to cover with zoom level and basic design/look of a webmap.

map = folium.Map(location=[36.2048, 138.2529], zoom_start=6, tiles="Mapbox Bright")

The numbers passed to the location argument are the global coordinates of Japan. We we load our map, it will zoom onto Japan automatically. If we keep on decreasing the zoom_start then the map will keep zooming out eventually displaying the whole world’s map. Increasing zoom_start will zoom into the map to point out a location as specific as a city or town or even a building located on a specific street. The tiles argument handles the design and look of the map. Folium has several custom tiles that can be used for specific situations. Now lets create an object from folium.FeatureGroup(). FeatureGroup() creates a new layer on top of the basic map. The layer can then be enhanced with markers and other visual elements. We can create as many layers as we want.

fgv = folium.FeatureGroup(name="Volcanoes")

Now we will create markers to display all the volcanoes. We have 100 volcanoes in our file so lets apply a for loop to iterate over the specific properties of each volcanoe.

for lt, ln, el, st, vnm in zip(lat, lon, elev, status, vname):
    fgv.add_child(folium.CircleMarker(location=[lt, ln], radius = 8, 
    popup= vnm + ", " + str(el)+" meters" + ", "+st,
    fill_color=color_producer(st), fill=True,  color = 'grey', fill_opacity=0.7))

Notice the zip() function here. The zip() function is a very useful function in Python that binds all the lists together and creates a seperate tuple for the properties for each volcanoe. It iterates over the “ith” element of each list creating i number of tuples in the end. Now we have 100 markers that take the properties of 100 different volcanoes from 100 tuples each displaying the different properties for that specific volcanoe. Awesome!

Now we call the method add_child() to add the feature group fgv to our map.

map.add_child(fgv)

And last but not the least, an object that controls the visibility of the layers on top of the map.

map.add_child(folium.LayerControl())

Lets save our final webmap result in an HTML file so that we can view it.

map.save("Japan-Volcanoes.html")

The Japan-Volcanoes.html file will be created in the same folder. This is our webmap. Lets view it.

webmap.jpg

If we click a marker, a popup will display the information of the corresponding volcanoe.

webmap-popup.jpg

The red volcanoes are active ones and yellow are inactive. Volcanoes bring us closer to the nature and remind us that our world was once an ocean of hot molten lava and then gradually it became cooler and beautiful as it is now :)

To learn more about Folium and leaflet.js webmaps read the online documentation of Folium. It is easy to understand and covers almost everything you can do with Folium. And with this we conclude our tutorial. I hape you have enjoyed it and learnt some cool things about Python. See you later. I have uploaded the volcanoes.txt file to Dropbox. You can access it here: https://www.dropbox.com/s/vu1mi2rj7hvkent/volcanoes.txt

Source code:

import folium
import pandas

data = pandas.read_csv("volcanoes.txt")
vname = list(data["Name"])
lat = list(data["Latitudes"])
lon = list(data["Longitudes"])
elev = list(data["Elevation"])
status = list(data["Status"])

def color_producer(stt):
    if stt == "Active":
        return 'red'
    else:
        return 'yellow'
        
map = folium.Map(location=[36.2048, 138.2529], zoom_start=6, tiles="Mapbox Bright")

fgv = folium.FeatureGroup(name="Volcanoes")

for lt, ln, el, st, vnm in zip(lat, lon, elev, status, vname):
    fgv.add_child(folium.CircleMarker(location=[lt, ln], radius = 8, popup= vnm + ", " + str(el)+" meters" + ", "+st,
    fill_color=color_producer(st), fill=True,  color = 'grey', fill_opacity=0.7))

map.add_child(fgv)

map.add_child(folium.LayerControl())

map.save("Japan-Volcanoes.html")

AUTHOR

Thank you for writing interesting articles. I am looking forward to sharing your knowledge.

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?