How I Integrated Folium with Django

Fateme Fouladkar
6 min readMay 1, 2023

--

When you wanna have interactive maps in your Django project without using any JS, Folium is the way to go! This handy python library lets you visualize your geospatial data on a map with just a few lines of python code. This way your users can benefit from viewing their desired places on a great-looking map.

The cover image showing a map with a marker on it, with Folium and Django logo together
Integration of Folium and Django

Using Foilum in a python script is just a piece if cake; but what if you need to use it in a django project? To uncover the details, keep reading; or just jump to How can we integrate Folium with Django?

  • Wanna know how you can have an interactive map in Django Admin Panel? Check this out:

What is Folium?

If you’ve worked with JavaScript, you might have heard about leaflet.js. Folium is a Python library which lets you use the power of leaflet.js in your geospatial projects. By using Folium, you could easily manipulate your data with python, and visualize it with leaflet.js maps (Without knowing any javascript!!).

an example of a Folium map

As it is stated in Folium documentation:

folium makes it easy to visualize data that’s been manipulated in Python on an interactive leaflet map. It enables both the binding of data to a map for choropleth visualizations as well as passing rich vector/raster/HTML visualizations as markers on the map.

How can we use Foilum to make maps?

As I said before, making a map with Folium is just a piece of cake. Let’s get straight to the code examples to see how easy it is.

1) Making the basic map

Start by installing the folium library:

pip install folium

Now import the library in your python script and make a basic map by specifying the latitude and logitude of the starting point:

import folium

map = folium.Map([40.416, -3.70]) # [lat, lon]

In order to see the result, you can save the map in an html file, or if you’re using a jupyter notebook, just ask for the object representation by calling map:

map.save("index.html") # save in a html file

map # ask for object representation (in jupyter notebook)
result of the Foilum map

There are multiple options you can add to your map:

map = folium.Map(location=[40.416, -3.70], # lat and lon of the starting point
width="50%", # width of the map
height="50%", # height of the map
zoom_start=12, # the staring zoom
tiles="OpenStreetMap", # desired tile for the map respresentation
zoom_control=True) # controls for zoom level (True by default)

You can choose one of many tiles for your map representation. Some of the available options are:

  • “OpenStreetMap”
  • “Mapbox Bright” (Limited levels of zoom for free tiles)
  • “Mapbox Control Room” (Limited levels of zoom for free tiles)
  • “Stamen” (Terrain, Toner, and Watercolor)
  • “Cloudmade” (Must pass API key)
  • “Mapbox” (Must pass API key)
  • “CartoDB” (positron and dark_matter)

2) Adding markers

Now let’s add a couple of markers to our map:

cloud_icon = folium.Icon(color='purple', # The color of the marker 
icon_color='white', # The color of the drawing on the marker
icon='cloud', # The name of the marker sign (checkout Font-Awesome v4 for more icon signs)
angle=0) # Rotation for the marker sign

first_marker = folium.Marker(location=[40.417, -3.70], # Latitude and Longitude of Marker
popup='this is my first marker! ', # Label for the Marker
tooltip='first marker', # Display a text when hovering over the object
icon=cloud_icon, # The Icon plugin to use to render the marker
draggable=True) # Set to True to be able to drag the marker around the map

first_marker.add_to(map)

The result would be like the below image:

Folium map with a purple marker in the middle

So far we only scrached the surface of Folium features. There are a ton of cool plugins and options in Folium that you can use to make astonishing maps. To get more familiar with Folium features, I strongly advise you to checkout the official documentation. The code examples we covered can be found on this google colab notebook.

How can we integrate Folium with Django?

In order to integrate your Folium map with Django, you’re gonna have to use TemplateView. Let’s clear things up by reviewing an example.

1) Add the view

The first step is to add a TemplateView to your views.py.

views.py:

from django.views.generic import TemplateView
import folium


class MapView(TemplateView):
template_name = 'map.html'

def get_context_data(self, **kwargs):
figure = folium.Figure()

# Make the map
map = folium.Map(
location = [40.416, -3.70],
zoom_start = 11,
tiles = 'OpenStreetMap')

map.add_to(figure)

# Add a Marker
folium.Marker(
location = [40.417, -3.70],
popup='integration of folium with django',
tooltip = 'folium and django',
icon = folium.Icon(icon='fa-coffee', prefix='fa')
).add_to(map)

# Render and send to template
figure.render()
return {"map": figure}

In order to load our map data into a django template, we need to manipulate get_context_data. Just make a Figure and add your Folium map to it. At last, the only thing that you need to do is to render the figure and send it out as context data to the template.

2) Get data from database

If you have come to the terms to integrate your Folium map with Django, it was probably because you needed to store and fetch the locations (markers) from the database. So let’s make a small change to our code here:

views.py:

from django.views.generic import TemplateView
from .utils import make_markers_and_add_to_map
import folium

class MapView(TemplateView):
template_name = 'map.html'

def get_context_data(self, **kwargs):
figure = folium.Figure()

# Make the map
map = folium.Map(
location = [40.416, -3.70],
zoom_start = 11,
tiles = 'OpenStreetMap')

map.add_to(figure)

# Fetch the objects from database and make Markers for them
for house in House.objects.all():
make_markers_and_add_to_map(map, house)

# Render and send to template
figure.render()
return {"map": figure}

We just loop through the objects we want, and for each of them, we make a marker and add it to our map.

utils.py:

import folium

def make_markers_and_add_to_map(map, house):
folium.Marker(
location = [house.latitude, house.longitude],
popup = house.description,
tooltip = house.title,
icon = folium.Icon(icon='fa-home', prefix='fa')
).add_to(map)

3) Add the map to template

Now it’s time to add our map to the template. Go ahead and make a template called map.html in your templates folder. If your stuck with configuring the templates in your django project, you can check out this article, or the official documentation.

map.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Houses</title>
{{map.header.render|safe}}
</head>
<body>
{{map.html.render|safe}}
<script>
{{map.script.render|safe}}
</script>
</body>
</html>

There you go! Now you can just define the url path for the map view and check it out on your browser.

In a nutshell

Folium is a great tool for when you want to show your geospatial data on a map with python. Using this library is super-easy and convenient. Plus, it’s got all the great features that you might need in your project.

Normally, you can get an html output of your Folium map; but by integrating Folium with Django, you’ll be able to fetch your data from the database. If you are looking for an example project with Folium and Django, you can check out this repository on Github. Also, feel free to follow me on Linkedin and Github.

--

--

Fateme Fouladkar

I'm a Python Back-end Developer who likes to write about the new trends and skills in the Software Development world.