None

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 http://www.brassbandresults.co.uk/map/.

Javascript

The javascript that specifies which points to show on the map is at http://www.brassbandresults.co.uk/map/map_script.js. 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 %}
     map.setUIToDefault();
    var mgr = new MarkerManager(map);
    var lBandMarkers = [];
{% for band in Bands %}
{% if band.latitude %}
{% if band.longitude %}
    lPoint{{band.id}} = new GLatLng({{band.latitude}}, {{band.longitude}});
    lMarker{{band.id}} = new GMarker(lPoint{{band.id}}, {title: "{{band.name}}"});
    GEvent.addListener(lMarker{{band.id}}, "click", function() {
        var myHtml = "<b>{{band.name}}</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.website}}'>Band&nbsp;Website</a>]";
        map.openInfoWindowHtml(lPoint{{band.id}}, myHtml);
    });
    lBandMarkers.push(lMarker{{band.id}});
{% endif %}     
{% endif %}
{% endfor %}
    mgr.addMarkers(lBandMarkers, 0);
    mgr.refresh();
   }
 }

Map Page

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

<script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=MY_API_KEY&sensor=false"></script>
<script type="text/javascript" src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></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