Login

Uk postcode googlemap templetag

Author:
_ben_
Posted:
February 23, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

Entirely based on and with big thanks to: http://www.tomanthony.co.uk/

Drops in a googlemap with a placemarker based on a uk postcode

Looks like this:

{% googlemap_from_ukpostcode postcode "XxY" zoom %}

e.g.

{% googlemap_from_ukpostcode "SP27AS" "220x290" 16 %}

postcode and zoom can optionally be template variables. "XxY" is the x/y size of the map you want to drop in. zoom can be omitted and defaults to 14.

requires: in settings: GOOGLE_AJAX_API_KEY, GOOGLE_MAPS_API_KEY google_map_ukpostcodes.js: is slight variation on js at http://www.tomanthony.co.uk/demo/geocode_uk_postcode/gmap.js

For further and better info see: http://www.tomanthony.co.uk/blog/geocoding-uk-postcodes-with-google-map-api/

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from django import template
from django.conf import settings


register = template.Library()



class GoogleMapNode(template.Node):
    
    def __init__(self,postcode='',xandy='',zoom=14):
        self.postcode = template.Variable(postcode.strip("\""))
        self.x, self.y = xandy.strip('"').split('x')
        self.zoom = template.Variable(zoom)
        
    def render(self,context):
        error = []
        if not hasattr(settings, 'GOOGLE_MAPS_API_KEY'):
            error.append('Google maps api not found')
        if not hasattr(settings, 'GOOGLE_AJAX_API_KEY'):
            error.append('Google ajax key not found')
            
        postcode = self.postcode.resolve(context)
        try:
            zoom = int(self.zoom.resolve(context))
        except:
            error.append('Zoom must be an integer')
        answer = '<script src="http://maps.google.com/maps?file=api&v=2&key=%s"type="text/javascript"></script>' % settings.GOOGLE_MAPS_API_KEY
        answer += '<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=%s" type="text/javascript"></script>' % settings.GOOGLE_AJAX_API_KEY
        answer += '<script>function get_postcode() { return "%s"; }</script>' % postcode
        answer += '<script>function get_zoom() { return %d; }</script>' % zoom
        answer += '<script src="%sjs/google_map_ukpostcodes.js" type="text/javascript"></script>' % settings.MEDIA_URL
        answer += '<div id="map" style="width: %spx; height: %spx; position: relative;"></div>' % (self.x,self.y)
        if error:
            return ', '.join(error)
        return answer
        
    
    
@register.tag
def googlemap_from_ukpostcode(parser,token):
    bits = token.contents.split()
    if len(bits) == 3:
        return GoogleMapNode(postcode=bits[1],xandy=bits[2])
    elif len(bits) == 4:
        return GoogleMapNode(postcode=bits[1],xandy=bits[2],zoom=bits[3])
    else:
        raise template.TemplateSyntaxError("'%s' tag takes two or three arguments, postcode, x/y size of map (e.g. \"100x200\") and zoom level" % bits[0])
    
    
=============

google_map_ukpostcodes.js


var map;
var localSearch = new GlocalSearch();

var icon = new GIcon();
icon.image = "http://www.google.com/mapfiles/marker.png";
icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);


function usePointFromPostcode(postcode, callbacks) {
	localSearch.setSearchCompleteCallback(null, 
		function() {
			if (localSearch.results[0])
			{		
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				for (var i=0;i<callbacks.length;i++) {
					callbacks[i](point)
					
				}
				return point;
			}else{
				alert("Postcode not found!");
			}
		});	
		
	localSearch.execute(postcode + ", UK");
}

function placeMarkerAtPoint(point)
{
	var marker = new GMarker(point,icon);
	map.addOverlay(marker);
}

function setCenterToPoint(point)
{
	map.setCenter(point, get_zoom());
}

function showPointLatLng(point)
{
	alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}

function mapLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		
		pc = get_postcode();
		
		//map.addControl(new GLargeMapControl());
		//map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(54.622978,-2.592773), get_zoom(), G_HYBRID_MAP);
		usePointFromPostcode(pc,Array(placeMarkerAtPoint,setCenterToPoint));
	}
}


function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
    }
  }
}

function addUnLoadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
	  window.onunload = func;
	} else {
	  window.onunload = function() {
	    oldonunload();
	    func();
	  }
	}
}

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.