Mathew K Analytics

Lesson 31 · Data visualisation in python

3 - Interactive Maps with Folium

In this lesson, you will learn to create beautiful, interactive maps in Python using the Folium library. We will start from the basics and build up to…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Welcome to Interactive Maps with Folium!#

In this lesson, you will learn to create beautiful, interactive maps in Python using the Folium library.

We will start from the basics and build up to displaying real-world locations and datasets.

By the end, you will be able to create and share your own interactive maps!

import warnings
warnings.filterwarnings("ignore")
try:
    from statsmodels.tools.sm_exceptions import ConvergenceWarning, ValueWarning
    warnings.filterwarnings("ignore", category=ValueWarning)
    warnings.filterwarnings("ignore", category=ConvergenceWarning)
    warnings.filterwarnings("ignore", category=RuntimeWarning)
except ImportError:
    pass

# Install folium if you do not have it
try:
    import folium
except ImportError:
    import sys
    !{sys.executable} -m pip install folium
    import folium

print("Python environment ready for Folium!")
Python environment ready for Folium!

What is Folium?#

Folium is a Python package for creating interactive maps.

With Folium, you can show markers, paths, and data right on the map.

It is used by scientists, journalists, and students to share location data.

# Let us create a simple map centered at a location.
import folium

m = folium.Map(location=[40.7128, -74.0060], zoom_start=12)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Let us add a marker: a point with a popup.
m = folium.Map(location=[37.7749, -122.4194], zoom_start=12)
folium.Marker([37.7749, -122.4194], popup="San Francisco!").add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook

How Do Coordinates Work?#

Maps use two numbers: latitude (north-south) and longitude (east-west).

For example, New York City is [40.7128, -74.0060].

You can find coordinates for any place using online tools.

# Let us let the user type a city name and add a marker for it.
city = input("Enter a city name (New York, Paris, Tokyo): ")
coords = {
    "New York": [40.7128, -74.0060],
    "Paris": [48.8566, 2.3522],
    "Tokyo": [35.6895, 139.6917]
}
if city in coords:
    m = folium.Map(location=coords[city], zoom_start=11)
    folium.Marker(coords[city], popup=city).add_to(m)
    m
else:
    print("Sorry, city not in list.")
    
# Let us add several markers for a mini road trip.
trip_cities = [
    {"name": "Seattle", "coords": [47.6062, -122.3321]},
    {"name": "Portland", "coords": [45.5122, -122.6587]},
    {"name": "San Francisco", "coords": [37.7749, -122.4194]}
]
m = folium.Map(location=[45.5122, -122.6587], zoom_start=5)
for city in trip_cities:
    folium.Marker(city["coords"], popup=city["name"]).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Let us draw a line to connect the trip cities.
m = folium.Map(location=[45.5122, -122.6587], zoom_start=5)
coords = [city["coords"] for city in trip_cities]
folium.PolyLine(coords, color="blue", weight=3).add_to(m)
for city in trip_cities:
    folium.Marker(city["coords"], popup=city["name"]).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook

Real-World Data: Visualizing Airline Passengers#

Maps can show both places and real datasets.

Let us map where airports are or look at travel numbers.

We will use a sample airline passengers dataset as an example.

# Data setup: Download and preview the airline dataset
import pandas as pd
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
df = pd.read_csv(url)
print("Dataset shape:", df.shape)
print(df.head())
Dataset shape: (144, 2)
     Month  Passengers
0  1949-01         112
1  1949-02         118
2  1949-03         132
3  1949-04         129
4  1949-05         121
# Let us see how passenger numbers changed over time.
import matplotlib.pyplot as plt
df["Month"] = pd.to_datetime(df["Month"])
plt.figure(figsize=(8,3))
plt.plot(df["Month"], df["Passengers"], marker="o")
plt.title("Monthly Airline Passengers")
plt.xlabel("Date")
plt.ylabel("Passengers")
plt.grid(True)
plt.tight_layout()
plt.show()
No description has been provided for this image
# Example: Plot US airport markers on a map (sample, not linked to dataset above)
us_airports = [
    {"name": "JFK Airport", "coords": [40.6413, -73.7781]},
    {"name": "LAX Airport", "coords": [33.9416, -118.4085]},
    {"name": "O'Hare Airport", "coords": [41.9742, -87.9073]}
]
m = folium.Map(location=[39.8283, -98.5795], zoom_start=4)
for airport in us_airports:
    folium.Marker(airport["coords"], popup=airport["name"]).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Add popups to your map markers with more info.
m = folium.Map(location=[39.8283, -98.5795], zoom_start=4)
for airport in us_airports:
    folium.Marker(
        airport["coords"],
        popup=f"{airport['name']}\nMajor US Hub",
        icon=folium.Icon(color="red", icon="info-sign")
    ).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Add a layer: show a circle for airport size (made-up size values for demo)
airport_sizes = [50, 70, 60]
m = folium.Map(location=[39.8283, -98.5795], zoom_start=4)
for airport, size in zip(us_airports, airport_sizes):
    folium.Circle(
        airport["coords"],
        radius=size * 1000,
        color="blue",
        fill=True,
        fill_color="blue",
        fill_opacity=0.2
    ).add_to(m)
    folium.Marker(airport["coords"], popup=airport["name"]).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Save your interactive map as an HTML file.
m.save("my_first_map.html")
print("Map saved as 'my_first_map.html'. Open it in your browser!")
Map saved as 'my_first_map.html'. Open it in your browser!
# Challenge: Ask the user for a city and add a marker!
city = input("Name your favorite city: ")
lat = float(input(f"Enter latitude for {city}: "))
lon = float(input(f"Enter longitude for {city}: "))
m = folium.Map(location=[lat, lon], zoom_start=10)
folium.Marker([lat, lon], popup=f"{city}").add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Pro tip: Use map layers to let viewers switch what they see.
m = folium.Map(location=[39.8283, -98.5795], zoom_start=4)
folium.TileLayer("Stamen Terrain", attr="Map tiles by Stamen Design, CC BY 3.0  Map data  OpenStreetMap contributors").add_to(m)
folium.TileLayer("Stamen Toner", attr="Map tiles by Stamen Design, CC BY 3.0  Map data  OpenStreetMap contributors").add_to(m)
folium.TileLayer("cartodbpositron", attr=" OpenStreetMap contributors & CartoDB").add_to(m)
folium.LayerControl().add_to(m)
for airport in us_airports:
    folium.Marker(airport["coords"], popup=airport["name"]).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Troubleshooting: What if you do not see your map?
try:
    m
except NameError:
    print("Looks like you have not created a map object called 'm' yet.")
    
# Best practice: Give your markers unique icons for easy reading.
icon_colors = ["green", "blue", "purple"]
m = folium.Map(location=[39.8283, -98.5795], zoom_start=4)
for airport, color in zip(us_airports, icon_colors):
    folium.Marker(airport["coords"], popup=airport["name"], icon=folium.Icon(color=color)).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
# Recap: What can you do with Folium maps?
print("With Folium, you can:")
print("- Show interactive maps in Python.")
print("- Add markers, popups, and lines.")
print("- Combine maps with real data.")
print("- Style maps with colors, layers, and icons.")
print("- Save your maps to share online.")
With Folium, you can:
- Show interactive maps in Python.
- Add markers, popups, and lines.
- Combine maps with real data.
- Style maps with colors, layers, and icons.
- Save your maps to share online.

You Did It!#

Now you can make interactive maps in Python.

Try making a map for your hometown, a favorite trip, or your dream places to visit.

If you enjoyed this lesson, like and subscribe for more beginner Python tutorials!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.