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”
Its good to see that you have shared such a simple script. Hope it will help me to materialize my market plan.
Thanks for the great tutorial, its been a good read and given some top information on how to get the google maps API to work better for us 🙂
I am trying to develop an online odering system, based around geographical areas for a new business of mine, have been trying to figure it out for weeks, have just found your site and has I guess driven me on the right track, still not sure, so will probably be back to ask some questions if that is ok…
Many thanks.
Thanks this tutorial is exactly what i needed thanks! I will be having a play later.
Hello, Tom. I am using your way of geocoding uk postcodes, which runs perfectly in IE8, but in IE7 and IE6, there are errors, and cannot show the map.
Have you noticed that?
Please run your own demo page under IE7 and IE6, and it will say two errors.
I wish you can see this. If your browsers are IE8, you can use IETester to see that under IE7/IE6. Many thanks.
I have been searching for some info on the Google Map API this is the best tutorial I have found so far – I have been getting no where until now.
Easily the best tutorial I’ve found for the Google Maps API – Thank you for the detailed information.
its very nice and really working good on my site
thank you very much tom. really nice tutorial…
very nice
Am looking for a free editable postcode map of the UK, I need each postcode area to be colour coded with my delivery charges. Is there anyone that can help me out
thankyou..perfect:)
Hi Tom great tutorial works great….. But only on one computer, works great on my macbook in which i developed it on) but not on my imac on the same internet connection.
if you have any thoughts is would be amazing – please help!
its displays the
“This web site needs a different Google Maps API key. A new key can be generated at http://code.google.com/apis/maps/signup.html.”
which i have seen others are getting but not working at all, I can get it to work on one but no other and I cant figure out why.
I am testing this on the link below
http://www.grenergysolar.com/map-stage1.html
Hi Tom great tutorial the best google api tutorial out there in fact, but….. i am having a slight problem, it works fine on the computer i built it on but on other computers it displays a messages saying i need to generate a new key, i think it might be some sort of permissions issue as it works fine on my computer. i have tested this on 3 other computers and the same massage id displayed
I am testing it on the link below
http://www.grenergysolar.com/map-stage1.html
any assistance would be much appreciated
Hi everyone! Thanks for all the feedback, and sorry to those who have asked questions that have gone unanswered. I’ve been so busy doing my PhD I’ve not had much time.
Will – it looks like you have the same key for both APIs, which I don’t think should be the case. Have you tried re-generating both keys with Google for the domain and checking they are correct? If you look locally at the files, then the keys are not necessary which would explain why you didn’t have a problem and do now.
HI Tom, Thanks for the quick reply, I have tried re-generating both api keys using both the links on here, which generate the same, both identical keys each time, resulting in it working on my computer but on the same url viewing on a different computer displays an error. How does the viewing it localy work if were viewing live on the same url. Could it mean its a server permissions error not letting google access the key in the server. I have strict access to upload file to the server through my ip. Im relatively new to google api UI, have viewed other examples using this example but i see nothing different with my code.
Any thoughts are much appreciated,
What you doing at PhD in?
Nice API Tom…
I have used it in some of my developments. Dead easy to intergrate into code etc…
This is a great article, thanks for the info. A lot og Google’s geographic ‘extras’ like ppc geo targeting are so inaccurate it is laughable.
[…] on March 19, 2011 by News We have followed Tom Anthony’s tutorial to calculate a geocode from a UK postcode to plot a marker on a Google Map. This has worked fine, […]
Hi Tom,
This is brilliant, I however, am having the same problem as .
I also had a look at your example link and you too have the same API key for the both.
Hope the PhD is going well!
Hi Will,
For your domain, I seem to get a different Map API key when I generate it: “ABQIAAAAsUBf7URfT5H6A5BoAwmjTxT_x5LtjaQDlJW7p7KCNn5Z_ufybxTQ
_vU5a0vnyvUw0sR77QEowvXR6A”. Maybe try with that? Hopefully it was just a hiccup.
My PhD is in Artificial Intelligence! A bit different to all this! However, I’m just writing up my thesis and then will be moving to full time working in the world of internet/digital marketing. 🙂
Daniel,
Have you got a link to the page, and I can try to take a look?
Thanks Alec and everyone else for the thanks messages. It is really cool to hear that people are using this. Silly situation that it is even necessary!
-Tom