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”
Thanks for taking the trouble to show us how to do this, but is it ok to use on a commercial site ?
Hi! You’re welcome. Yes, it is absolutely fine to use it on any site. 🙂
Nice article. Thanks for sharing
Great tutorial Tom, thanks for the info.
Informative article. Thanks
This is a great solution but do you have a set of code for v3? I am using Geonames but the response is often too slow to update and the standard in Google does not provide a full postcode.
Hi Tom, thanks for this. You know I’m so so glad that it labels the North Sea on the initial map. Just incase people forget where it is. It’s a pretty useful feature google have added. Do you know when it was added?
Thanks again.
Hi guys we just wanted to let you know if anybody is looking for a simpler solution to this with Google streetview included as well as map view give us a shout. Were selling the complete script integrated into your site for £20.
Thank you so much for providing such a wonderful article
Hi Tom,
I have been working on an asp.net webapplication. My requirement is to integrate google maps using uk postal code in my site. Currently I am running my appplication in local machine. It is not showing any map right now.
actually localSearch.setSearchCompleteCallback() is not invoking , is it because i am running app in local machine or any other reason . One more thing i have generated keys for this using one of my other site and both keys are same right now.
Please help me on this
Thank you in advance
Is the code still working properly? , I get US places appear on the map. Also words such as ‘nothing’ aren’t being returned as false. Thanks
hemanth – It should work locally. Try using a few alert() statements to get feedback on what is going on. Try also making a demo of just the maps and just the local search (separate) so you can narrow down where the problem might be.
Wilfred – Can you give me some example postcodes that show in the US?
I don’t know if it’s a US postcode but if I enter ‘red’ it centres the map to location in what appears to be San Fransico.
OK – but it is unlikely you ever need to geocode the word ‘red’. So I’m guessing you have a list of addresses that need to be geocoded and some don’t work?
yea, i was using it as postcode validator, so people fill in a valid postcode
Excellent tutorial, it’s a shame you can’t get the country.
Thanks for this. It was perfect for what I needed to get me started pre-populating a form from a postcode. If anyone is interested head over to the google api docs to find out what else you can grab. Couldn’t get the street unfortunately, but this might be a Royal Mail licencing issue?
Thanks again for the great bit of code to start me off.
Thanks for this, looks to be just what I was searching for.
BTW
AFAIK
The ajax key is the same as the API key
Do I need permission from google to use this ?