Notice: As a few people have pointed out, this announcement from Google means Geocoding is now built in. Yet as more people have pointed out – it kinda sucks accuracy wise (think over a mile off on some postcodes!), whereas my method continues to be accurate.
Google Maps API provides a geocoding feature, for finding the latitude and longitude of places or addresses; but it does not work for UK postcodes. This is thanks to Royal Mail who have a copyright on the data, and are very restrictive with their (expensive) licenses for it.
There are various solutions out there for using 3rd party services and importing the data to be used with Google Maps, or for using community built databases for the info. However, I’ve had a few people ask me about doing it just though Google.
It is possible — Google AJAX Search API does provide geocoding for UK postcodes. We need to use the two APIs in harmony to achieve our result.
So here it is.
Step by step
I’ll assume you already know how to use Google Maps API, and you came here just looking how to add geocoding for the UK.
Step 1.
Grab a two API keys, if you already have your Google Maps API key, just grab an AJAX search key. You can get them here:
http://www.google.com/apis/maps/signup.html
http://code.google.com/apis/ajaxsearch/signup.html
Step 2.
Google will give you a sample page, you need to stick your two API keys at the top of the page, followed by a reference to your Javascript file:
<script src="http://maps.google.com/maps?file=api&v=2&key=*KEY*" type="text/javascript"></script> <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=*KEY*" type="text/javascript"></script> <script src="gmap.js" type="text/javascript"></script>
Ensure the reference to your Javascript file comes after the two API keys.
Step 3.
In addition to the Google Maps API stuff, you need to stick a reference to Google local search at the top of your Javascript file:
var localSearch = new GlocalSearch();
You can grab my Javascript file right here, but remember you’ll need to change the API keys.
Step 4.
The key to this Geocoder is only a single function:
function usePointFromPostcode(postcode, callbackFunction) { 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); callbackFunction(point); }else{ alert("Postcode not found!"); } }); localSearch.execute(postcode + ", UK"); }
It takes 2 arguments; postcode
is the postcode you want to look for, and callbackFunction
is the function you wish to run on the results.
Why is it necessary to do it this way? It is the way AJAX, and thus Google AJAX Search API, works – the request is sent, and a callback function is designated to handle the results returned, when they are ready.
In our case, the callback function can do whatever you want with the results, which will come in the format of a GLatLng
(often just called a point); I’ve supplied 2 sample functions, placeMarkerAtPoint
and setCenterToPoint
which do pretty much what they sound like they do.
Step 5.
Putting aside accessibility and graceful degradation for the sake of simplicity in this tutorial, the last step we need is just to add some hooks into our Javascript:
<input type="text" id="postcode" size="10" /> <input type="submit" value="Place Marker" onclick="javascript: usePointFromPostcode(document.getElementById('postcode').value, placeMarkerAtPoint)" />
We have a field for inputting a postcode, and I’ve added a button for placing a marker there. Where I have placeMarkerAtPoint
you can put a reference to your own function, or you can even add a function right in there, like this:
<input type="submit" value="Do whatever" onclick="javascript: usePointFromPostcode(document.getElementById('postcode').value, function (point) { alert('Latitude: ' + point.lat() + '\nLongitude: ' + point.lng()); })" />
Demo
If you are coming in from an RSS reader, either visit this blog post on the site, or see the demo page.
Postcode:
Conclusion
Until Royal Mail sort get their act together, and relax the licensing agreement, hopefully this will help people who want a ‘pure’ Google solution and hadn’t come across this option. Please use the comments section to let me know if you are using this, or if you have any improvements or suggestions.
378 responses to “Geocoding UK Postcodes with Google Map API”
Tony,
Please do. I’d like to see how you implement this.
I am using Tom’s technique with Ruby on Rails. The plugin I’m using for ‘find your nearest’ functionality is http://geokit.rubyforge.org/.
I’m currently writing up a tutorial on this. I’ll trackback to this post once it is done.
Xin
Tony,
That sounds great. I’ve had no call for this yet, but a client of mine may need it soon. I have a couple of ideas for how the algorithm might work, but would love to see how you would implement it!
Xin,
Please do! It would be a great resource! 🙂
[…] Tom Anthony’s has written an excellent article called Geocoding UK Postcodes with Google AJAX Search API. […]
Is any one else having problems getting the ‘Place Marker’ function to work.
Tried this several times and im getting nothing.
Does this usage abide by royal mail copyright conditions? i.e. can i use it on a corporate intra-net? I guess this depends on weather google have paid for Royal Mails stupid copyright on postcodes latLongs.
do you know anything about this? or have any links to info on it?
Rob
I think the answer is no.
Read the Google MapAPI Terms and you will see that this sort of thing is not allowed – although you did say intranet and therefore who would know?
You need to check this out for yourself and make a value decision for yourself.
Tom – how about a contact me link on your site?
Rob
I think you need to check out the terms and conditions on Google – be carefull not to just look at the terms for Google Maps – they have to be taken in conjunction with the Terms for Goole its self and as this takes advantage of the AJAX search API you need these Terms as well – thre is some repetition BUT they all have something unique – there is also 3rd party considerations to be taken into account as well – I cat remember who all the parties are but for example NAVTEC and Yell have writes to do with their data…
I see you want it for an Intranet – but as you are then pulling in others info you need to be carefull.
Sorry not to be more supportive but every sitation is different and it depends on what you are trying to do – and the results of this action.
David-
Contact link is a good idea; I’m actually working on a complete site, but a so busy making other peoples websites, I haven’t time for my own!
Hopefully it will be up soon, and I’ll have time to write some more tutorials too.
Rob,
I agree with David & Eric, tread carefully. Though your situation is unique, so who knows. Let us know if you find out for sure.
I found this:
http://www.google.com/intl/en_ALL/help/terms_maps.html
which states
\”Also, you may not use Google Maps in a manner which gives you or any other person access to mass downloads or bulk feeds of numerical latitude and longitude coordinates.\”
might be relevant to some around here….
Im still getting the same problem that the PalcceMarkerAtPoint function is not placing a marker.
Re-entered the code several times and re-downloaded the gmap.js file – same thing.
Cleared the cache.. etc etc. Nothing
Any clues what i am doing wrong?
Thanks for this useful stuff
BTW In step 1, the two google keys appear to be the same
hi, i want search by house number and postcode (like http://www.skiclub.co.uk/skitv/subscription/subscribe.asp ), can you help me?
Hi Tom,
Thanks for sharing this code with us. I am trying to use your code, ofcourse after replcaing the key, but the map doesn’t load for me. There is no such error but the map doesn’t get displayed on the page. Any idea if there is more to change in your code apart from changing the key? Also can we use this by passing address instead of postcode?
Thanks
Prashant
Hi Tom,
I have a couple of sites based on the chauffeur industry and have been looking for a instant quoting system.
I have a simple system at present which is not accurate!
I have got a backend mileage calculator which I can set different rates for pence per mile which is fine.
What I need is an accurate A to B with the correct mileage and take this value and put into my calculator to get a Price.
I recently installed google maps and let people enter in the directions and then ask the customers to enter the mileage shown on the google results and enter the mileage into the calculator to get a price.
It would be nice to have something similar to this http://www.ecourier.co.uk .
I am just playing with a joomla site at the moment and am learning how it all works so many add ons and modules.
Is there a way of extracting the google mileage and to place it into a calculator to get a instant quote or do you have you any idea’s how this can be done!
Any advice would be great
Malcan
Sorry Tom Put in wrong url
http://www.ecourier.co.uk/eCourierISAPI.dll?quote&id=2555232-37895456
Regards
Malcan
We have tested the code as above but problems with UK data – the response we get is:
–
–
England
–
603
geocode
I’m not sure if things have changed since this message was posted?
Any help would be appreciated?
Tks
Dan
Hello Tom.
Very good tutorial about UK postcodes. I’m looking for something different. I’d like to have a possibility to read a town or a postcode from the marker placing on the map (I mean latitude and longitude point = town or village). Thanks in advance for an advice.
Its working for me thank you very much. its really charming. Do you know if we can use this in a business website where everybody can access it ?
And also I have one more question. Lets say some one put a post code. Is it possible to recieve a string of street address instead of Long and lat ? if yes where can I find this method ? or what is it ?
Thank you again for sharing this. Lovely.
hi Tom,
i had some error while try this code, the error is
GlocalSearch is not defined
can you help me to solve this problem???
thanks.
hi, Tom
i had trouble with your javascript code, when i try it in my browser the error says that GlocalSearch is undefined. is it Google AJAX Search API only can used on server in UK??? can you help me for resolve this problems???