Django Folium: How to Display Saved Locations on a Map

In web applications, it’s often useful to display saved locations on a map. Django, a high-level Python web framework, combined with Folium, a powerful Python library for creating leaflet maps, provides an elegant solution for this task. In this tutorial, we’ll walk through the process of displaying saved locations on a map using Django-Folium. Additionally, we’ll create the map within the view code itself.

an example of a Django Folium map

Prerequisites:

  • Python and Django installed on your system.
  • Basic knowledge of Django and Python.
  • Familiarity with HTML, CSS, and JavaScript.

Getting Started

  • Setting Up the Django Project

First, let’s create a new Django project and set up a Django app within it.

Bash
django-admin startproject map_project
cd map_project
python3 manage.py startapp map_app

Next, we need to install Folium.

Bash
pip install folium
  • Creating the Model

In our Django app (map_app), let’s create a model to represent the locations we want to display on the map. Open map_app/models.py and define the model as follows.

from django.db import models

class Location(models.Model):
    name = models.CharField(max_length=100)
    latitude = models.FloatField()
    longitude = models.FloatField()

    def __str__(self):
        return self.name

Don’t forget to run migrations after creating the model.

Bash
python3 manage.py makemigrations
python3 manage.py migrate
  • Creating the View

Now, let’s create a view to display the map with saved locations. Open map_app/views.py and define the view.

from django.shortcuts import render
import folium
from .models import Location

def map_view(request):
    # Get all saved locations from the database
    locations = Location.objects.all()

    # Create a Folium map centered at a certain location
    map = folium.Map(location=[locations[0].latitude, locations[0].longitude], zoom_start=10)

    # Add markers for each location
    for location in locations:
        folium.Marker([location.latitude, location.longitude], popup=location.name).add_to(map)

    # Render the map within the view code
    map = map._repr_html_()

    return render(request, 'map.html', {'map': map})
  • Creating the Template

Now, let’s create a template (map.html) to render the map. Create a new file map.html inside the map_app/templates directory.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Map</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <style>
        #map {
            width: 100%;
            height: 600px;
        }
    </style>
</head>
<body>
    <div id="map">{{ map|safe }}</div>
</body>
</html>
  • Configuring URLs

Lastly, let’s configure the URL routing. Open map_project/urls.py and define the URL pattern for our view.

from django.contrib import admin
from django.urls import path
from map_app.views import map_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', map_view, name='map_view'),
]

Now, you can run the Django development server.

Bash
python3 manage.py runserver

Visit http://127.0.0.1:8000 in your browser, and you should see the map with the saved locations displayed as markers.

That’s it! You’ve successfully displayed saved locations on a map using Django Folium, with the map created within the view code itself.


Leave a Reply

Your email address will not be published. Required fields are marked *

DarkLight
×