Django Google Maps Multiple Markers Example

Published On: 27/08/2022 | Category: Django


Hi Dev,

This tutorial is focused on django google maps multiple markers. you can understand a concept of how to add multiple marker in google map in django. This tutorial will give you simple example of django add multiple marker in google map. you will learn how to show markers location in google map dynamically from database in django.

In this example, we will create one simple urls and display google map with marker. We will use the google maps js library for adding google map. you can easily add a google map in django all versions.

you can see bellow preview, how it looks:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App

Now we'll create a single app called core to display our google maps multiple marker. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core
Step 3: Update setting.py

In this step we require to do here, do not forget to register the new app in the settings.py file. under installed apps, just add ‘core’ to the list:

And, here, we will add new variable in setting.py file fo set GOOGLE_MAPS_API_KEY. so let's add as bellow:

Next, you need to add it in the settings.py file as follows:

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

....

GOOGLE_MAPS_API_KEY=YOUR_GOOGLE_API_KEY

Django Admin Interface:



Step 4: Creating the Views

In this step, we need to configure our five views. The maps_view page will just be a template and get the all records from Location table. and pass with google maps api keys open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from django.conf import settings
from .models import Location
import json

def maps_view(request):
    data = Location.objects.values('name', 'latitude', 'longitude')
    json_data = json.dumps(list(data))
    return render(request, 'googleMap.html', {"data": json_data,'google_maps_api_key': settings.GOOGLE_MAPS_API_KEY})
Step 5: Creating the Templates

Next, open the core/templates/googleMap.html file and the add:

core/templates/googleMap.html
<!DOCTYPE html>
<html lang="en">
    
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django Google Maps Multiple Markers Example - Tuts-Station.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
    <style type="text/css">
        #map {
          height: 400px;
        }
    </style>
</head>
    
<body>
    <div class="container mt-5">
        <h2>Django Google Maps Multiple Markers Example - Tuts-Station.com</h2>
        <div id="map"></div>
    </div>
    
    <script type="text/javascript">
        function initMap() {

            var locations = {{ data|safe }};
            
            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 5,
                center: { lat: 22.2734719, lng: 70.7512559 },
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
  
            var infowindow = new google.maps.InfoWindow();
  
            var marker, i;
              
            for (i = 0; i < locations.length; i++) {
                  marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i]['latitude'], locations[i]['longitude']),
                    map: map
                  });
                    
                  google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                      infowindow.setContent(locations[i]['latitude']);
                      infowindow.open(map, marker);
                    }
                  })(marker, i));
  
            }
        }
  
        window.initMap = initMap;
    </script>
  
    <script type="text/javascript"
        src="https://maps.google.com/maps/api/js?key={{ google_maps_api_key }}&callback=initMap" ></script>
  
</body>
</html>
Step 6: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from core import views

urlpatterns = [
    path('map/', views.maps_view, name="maps_view"),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/map address with a web browser.

I Hope It will help you....