Simple Google Maps with Django

November 26, 2009

Here's a simple example of using Google Maps with Django. The map in question is online at


The javascript that specifies which points to show on the map is at This is generated using the following django template:

function initialize() {
   if (GBrowserIsCompatible()) {
     var map = new GMap2(document.getElementById("map_canvas"));
{% if Band %}
     map.setCenter(new GLatLng({{Band.latitude}}, 
{{Band.longitude}}), 12);
{% else %}
    map.setCenter(new GLatLng(53.800651, -1.454), 8);
{% endif %}
    var mgr = new MarkerManager(map);
    var lBandMarkers = [];
{% for band in Bands %}
{% if band.latitude %}
{% if band.longitude %}
    lPoint{{}} = new GLatLng({{band.latitude}}, {{band.longitude}});
    lMarker{{}} = new GMarker(lPoint{{}}, {title: "{{}}"});
    GEvent.addListener(lMarker{{}}, "click", function() {
        var myHtml = "<b>{{}}</b><br/>{% if band.rehearsal_night_1 %}Rehearsals {{band.rehearsal_nights}}{%endif%}<br/>[<a href='/bands/{{band.slug}}/'>Contest&nbsp;Results</a>] [<a target='_blank' href='{{}}'>Band&nbsp;Website</a>]";
        map.openInfoWindowHtml(lPoint{{}}, myHtml);
{% endif %}     
{% endif %}
{% endfor %}
    mgr.addMarkers(lBandMarkers, 0);

Map Page

The main page that displays the map includes the following javascript imports:

<script type="text/javascript" src=";v=2&amp;key=MY_API_KEY&sensor=false"></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src="/map/map_script.js"></script>

Then all that's required is to place a div to place the map in:

<div id="map_canvas" style="width: 100%; height: 450px"></div>

and ensure that the map is set up when the page is loaded, so add an onload event to the tag:

<body onload="initialize()">

Tags: django google maps