Geocoding UK Postcodes with Google Map API



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.




USER COMMENTS ( 392 )

Follow Comments via RSS feed. Trackback Comments from your website.

  1. Tino April 9, 2009 REPLY

    Wow this is great, its really what I was looking for.

    I have a slight problem though, on a basic HTML page the code workd fine but when I place it on an asp.net form I cant get it to work.

    I read further up the thread and tried what one user suggested, to put runat=server in the controls, i tried it in the input tag and the others too but still cant get it working.

    Any one cast any light?

    Thanks

    Tino

    aspx

  2. Tim S April 10, 2009 REPLY

    heres a little something created with similar geocoding. This is a google / ebay api mashup and pin points used cars for sale via Ebay auction listings. Have a go! http://www.find-cars-4-sale.co.uk/

  3. Tino April 15, 2009 REPLY

    Would it be possible to provide an example using RESTful interface returning JSON object for ASP.NET C#?

    I belive it supports the GET method

    Regards

    Tino

  4. Jim April 23, 2009 REPLY

    This is great. It also shows great weaknesses in my understanding of javascript.

    Try as I might, I can’t figure out how to make the system work off a postcode variable. As stated, onload doesnt work as a method to trigger the map to use a postcode. I cant find a place / modification which loads themap according to a postcode variable either.

    I am obviously being thick. Does anyone know/already have a variant of this code which works from a postcode variable passed to the code (or even a hardwired postcode rather than coords)?

    Many thanks if anyone can help with this, it is driving me mad…

  5. Jim April 23, 2009 REPLY

    Oops.

    Thanks so much Martin, I failed to see your link (just about as well as I failed to find the information elsewhere!!)! For those looking for the exact code to display a map by postcode variable without a click, as Martin above pointed out, the solution is here:

    http://forum.websitebaker2.org/index.php?topic=12846.0

  6. Alec April 25, 2009 REPLY

    Well thanks to Tom’s tutorial I’ve finally managed to get driving directions with accurate start and end points using the Google Maps API. It’s only taken me a year to work it out.

    Here’s an example for anyone struggling with the same thing http://www.anywherecouriers.co.uk/maps/directions-with-uk-geocoding.html

    It’s probably not the most elegant solution but it works and I’m happy.

  7. Noms April 30, 2009 REPLY

    Thanks very much for this article Tom.. I have also made some additions to it like adding reverse geocoding.. getting address details from latitude and longitude.

    However, is there a possibility we can create a dll or a webservice that does that.. What i am trying to say since it uses Ajax/javascript that runs only on client side.. can we trick a page into thinking that it has been rendered on the browser to invoke the javascript..

    I have been trying to find a way to do that but have not been successful.

    Not sure if anyone else has tried it yet. if so do let me know..

  8. stefan May 9, 2009 REPLY

    great info, thanx
    Puppies for sale

  9. Ibrar May 11, 2009 REPLY

    Hi, thanks for Great tutorial.

  10. Andrew May 12, 2009 REPLY

    I am have a problem all to piont i put on the map have the same text can some see what i am doing wrong

    function usePointFromPostcode(postcode,ref) {
    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);

    var marker = new GMarker(point);

    GEvent.addListener(marker, “click”, function() {
    marker.openInfoWindowHtml(InfoText[ref]);
    });
    map.addOverlay(marker);
    }
    else {
    /* SKIP THAT PROPERTY CUZ I CAN’T FIND IT! */
    }
    });

    localSearch.execute(postcode + “, UK”);

    }

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

    }

    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);

    Welcome back Andrew here are you jobs for today

    var InfoText=new Array();
    InfoText[0] = ‘Job No. 3 Name : Price Phone ew’;alert(“0″);
    usePointFromPostcode(‘wa1 0py’, ’0′);
    InfoText[1] = ‘Job No. 4 Name : 1 Phone 1′;alert(“1″);
    usePointFromPostcode(’1′, ’1′);
    InfoText[2] = ‘Job No. 4 Name : Tim Phone 1′;alert(“2″);
    usePointFromPostcode(‘WA4 0Py’, ’2′);
    InfoText[3] = ‘Job No. 4 Name : a Phone 1′;alert(“3″);
    usePointFromPostcode(‘WA2 0PY’, ’3′);
    InfoText[4] = ‘Job No. 4 Name : Price Phone ew’;alert(“4″);
    usePointFromPostcode(‘wa3 0py’, ’4′);
    InfoText[5] = ‘Job No. 4 Name : price Phone 11′;alert(“5″);
    usePointFromPostcode(‘PO45 2ah’, ’5′);
    InfoText[6] = ‘Job No. 4 Name : aa Phone 1′;alert(“6″);
    usePointFromPostcode(’1′, ’6′);
    InfoText[7] = ‘Job No. 4 Name : 1 Phone 1′;alert(“7″);
    usePointFromPostcode(‘WA2 0PY’, ’7′);
    InfoText[8] = ‘Job No. 4 Name : 2 Phone 1′;alert(“8″);
    usePointFromPostcode(‘S70 4ST’, ’8′);

  11. Polskie Firmy May 19, 2009 REPLY

    Many thanks for this great tutorial! Exactly what I was looking for :)

  12. Sean May 28, 2009 REPLY

    I had the same problem as Stew (June 7, 2007 @ 9:27 pm) and Matt (June 11, 2007 @ 4:20 pm)

    The page loaded with the buttons (map, satellite, hybrid, and the pan zoom buttons), but no actual map… just a blank white background.

    I even followed Tom’s advice and copied the the files from the demo page:
    http://www.tomanthony.co.uk/demo/geocode_uk_postcode/

    Still no joy.

    Then I noticed the htm file ends with
    <div id=”map”

    I replaced this with

    And bingo – it works.

  13. Sean May 28, 2009 REPLY

    Sorry, code didn’t come out.

    I replace id=”map”

    with

    id=”map” style=”width: 700px; height: 450px”

    and this worked

  14. Gumbo June 2, 2009 REPLY

    Nice, simple and clean.

    thanks for a great tutorial.

    Cheers!

  15. rob ganly June 6, 2009 REPLY

    >>but no actual map… just a blank white background.

    the reason it comes out blank is because the map is styled [sized] in the css file, and by just copying the source you won’t have this styling info.

    the quickest way to remedy this to get the demo working locally is to just put the style inline in the head of your doc.

    #map
    {
    height: 500px;
    width: 500px;
    }

    hope that helps.

    rob ganly

  16. JMM June 8, 2009 REPLY

    Got the code working no problem and thanks very much for providing.

    I am looking to embed the map into a PDF created from Coldfusion. When I add in the working code it produces nothin on the PDF.
    Anyone any ideas?

  17. [...] Geocoding UK Postcodes with Google Map API | Tom Anthony – [...]

  18. Aron Draper June 15, 2009 REPLY

    I used your code a long time ago and has been working for well over a year but today it ha sstopped working and can see that the one on this site has stopped working too with the same errors fro JavaScript. Im gussing there will be a few people with this issue.

    Im currently looking for an answer and will post her eif I find something.

  19. Aron Draper June 15, 2009 REPLY

    A change must have been made with the API or a Windows update becase all the maps Ive looked at today that used this tutorial have now stopped working.

    Ive been trying to find an answer to no avail. The error is that the map doesnt display at all and you get some javascript errors referrign to localsearch and glocalsearch.

    Anyone with a fix it would be greatly appreciated.

  20. Julie June 16, 2009 REPLY

    Hi,
    I have a small B & B business and when my guests use sat nav to find me it takes them 400/500yds away from me, where there are only two houses. I am one of four and one of them is a pub. Can you help or advise me on how to get this changed. Just spent an hour on google and got nowhere. I’m not very technically minded, so please keep it simple !!!!!
    Thank you
    Julie

  21. AD June 22, 2009 REPLY

    I am wondering, does this API actually validate postcodes.

    IE:
    Apartment/Lodger Website where users need to enter in a postcode, which provides a Google map reference; therefore a Postcode is used to validate the location and create a map location at the same time.

    What happens if the postcode is invalid? Will it be able to catch it and display it on the screen (or return it in some other way), rather than accepting it?

    Thanks.

  22. Max Manders June 22, 2009 REPLY

    Hi,

    I’m working on a personal site that uses the Google Maps API. The postcode the user submits is used to make an AJAX call to a home grown API that returns among other things, a load of postcodes in XML. I then iterate over these postcodes and place markers for each of them, i.e. all the postcodes that are related to the user-entered postcode.

    However, I presume the localsearch performs asynchronously, and as such, some of my postcodes aren’t being geocoded – I believe because the previous localsearch hasn’t returned).

    My code is something like:

    [code]
    for (var i = 0; i < stores.length; i++) {
    var postcode = stores[i].getElementsByTagName('postcode')[0].childNodes[0].nodeValue;
    usePointFromPostcode(postcode, placeMarkerAtPoint);
    }
    [/code]

    There are 5 postcodes in my XML being output by Firebug, but only the first and last are successfully geocoded. Any thoughts?

  23. Adam Binno June 24, 2009 REPLY

    Hi,

    Thanks for the great tutorial and demo. I would have never thought to use the ajax search with google maps but it seems to work pretty well, not sure how accurate some of the results are which are returned by google tho.

    Thanks

  24. Martin Babcock June 25, 2009 REPLY

    Do you wish you could increase your online leads? Getting a 1st page Google ranking is easier and more cost-effective than you might think. We have helped a lot of businesses thrive in this market and we can help you! Simply hit reply and I’ll share with you the cost and the benefits.See you at the top!

  25. sophie July 23, 2009 REPLY

    Hello, i tried to find my friends house by using her postcode on google and it didnt work…:(

  26. Michael July 29, 2009 REPLY

    Tom,

    A FANTASTIC tutorial there. I’m very impressed and have had little to no problems in implementation. However (you KNEW that was coming)… There is still a MASSIVE problem with accuracy in the data I’m getting back from google. If I may give an example: GU5 0HF comes back as 51.193548,-0.557244 when it SHOULD be 51.193608,-0.556999.

    Is there something just inherently WRONG with googles data?

  27. Me August 4, 2009 REPLY

    Michael, according to Royal Mail (who should know) GU5 0HF is High Street, Bramley, which Google correctly positions at 51.193548,-0.557244. 51.193608,-0.556999 is in Windrush Close, Bramley, which Royal Mail identifies as GU5 0BB. Google reverse geocodes this to 23-37 Windrush Close, Bramley.

  28. Wiredworx August 15, 2009 REPLY

    Great tut! Helps me out loads! Thanks a lot.

  29. Rhys August 30, 2009 REPLY

    I’ve just completed an adaptation of this to accurately geocode a batch of uk postcodes: http://wheresrhys.co.uk/2009/08/geocoding-in-the-uk/

  30. Timbo September 2, 2009 REPLY

    Fantastic – thanks, this is way more accurate than the Maps API.

  31. Basil Jose September 18, 2009 REPLY

    Is there any way I can calculate the UK postsode to postcode distance using google maps?

  32. Gareth Moss September 24, 2009 REPLY

    Hey, great article, but have you noticed the search doesn’t work anymore, I’m guessing google have changed something as my site and yours doesn’t work. :-S

  33. Oh No September 24, 2009 REPLY

    This stopped working for me recently too!!! Oh no!!!!

  34. ksc1919 September 29, 2009 REPLY

    Thank you for your script.
    I got cache.php and geocode.php working fine. Just not clear how/where I add the 2 functions together in step 4 & 5. Appriciate some guidance. Thanks in advance.

  35. Phil Howard September 30, 2009 REPLY

    This script is just what i was looking for.
    I’m trying to make a link through to a google map from a dynamic page based on the postcode info for each entry in a mysql database. I’ve tried using the php method you suggested earlier but i’m stuggling to get it to work.
    I’ve got the postcode from the url using GET but I don’t know where in the script to put the actual postcode so that the map loads centered on the postcode from the url rather than the GLatLng in the mapLoad function.

  36. ksc1919 October 1, 2009 REPLY

    Is there a zip file containning sample script I can download to have a look at? thanks

  37. James Hancock October 6, 2009 REPLY

    Anyone have any suggestions how I could use this to get all of the applicable addresses in a zip? I.e. I want to not have to pay royal mail a fortune for simply getting the town/city from a post code (possible address list would be even better).

    Thanks!

  38. Leigh October 8, 2009 REPLY

    The accuracy of this data returned is now rated a “5″ – The same as that of the Google Maps API :(

  39. Leigh October 8, 2009 REPLY

    …but on closer inspection, it definitely still gives more accurate results!?

  40. Payman October 15, 2009 REPLY

    As part of a research project, I gathered an exhaustive list of all full UK postcodes (just under 2 million records) with their latitude and longitude.
    If you’re interested in purchasing it then contact me via payman_labbaf [at] yahoo.com.

  41. Website Development October 27, 2009 REPLY

    nice example

  42. software consultants uk October 27, 2009 REPLY

    Great will use it easily now

  43. Nick Wood October 28, 2009 REPLY

    Google have awful accuracy and DO NOT provide Geocoding. The maps do lack detail adn their premier programme (enterprise is a staggering £7700 and is not great compared to ViaMichelin solutions ) I know this from experience !

    This has taken me so long to access and my developers have been flat out for months if finding a provider in the UK who offer Geocoding, reverse geocoding distance calculation, map management, route calculation with excellent maps and mapping technology)and accuracy. Coverage was key in choosing ViaMichelin too as they are a respected brand.

    Google lacked support and the Geocoding was very expensive and not great. The other local providers could not stand up and deliver what is needed for me working in the transport industry as good logistics can save you money.

    ViaMichelin were so cost effective I saved thousands of what I would ahev paid elsewhere and have a flawless solutions which has allowed me to win many more clients. I would highly recommend VIAMICHELIN API (store locators, Journey planners, directions, toll charges, congestion charge London and Live traffgic info) and the contact there is MARK who came to meet me to discuss my needs, there was no pressure and when I had all the info from 4 companies, It was a no brainer in choosing ViaMichelin Business Mapping and Geolocation for my GIS Geocoding web based webservices platform, It did not take long to developer inhouse and they host it too

  44. Zeeshan Ahmad October 29, 2009 REPLY

    Hi,
    Thanks for this article but one more thing. Can we get the textual address by giving postal code? Is it possible? Just like point.lng(); , how can i get the textual address and the detail like street name etc. If possible then please help me.

  45. Zeeshan Ahmad October 29, 2009 REPLY

    Hi Paul,
    Thanks Dear. I got it.

  46. Fred Smith October 29, 2009 REPLY

    So is it possible to have a post code search whereby the webiste visitor could find a shop within x number of miles from his house? Without having to go to the Post Office?

  47. Best Free Ads November 2, 2009 REPLY

    Nice guide bud!

  48. same day courier service November 3, 2009 REPLY

    I believe the royal mail website has this facility.

  49. Rob November 16, 2009 REPLY

    I have a problem where I can either set a marker, or I can center the map. When I do both, then only the second one works.

    {
    usePointFromPostcode(“NW11AA”, placeMarkerAtPoint);
    usePointFromPostcode(“NW11AA”, setCenterToPoint);
    }

    No marker will be shown for the above..

  50. William November 17, 2009 REPLY

    Hi Tom, when I switch to the Map view on your site, all I get is a grey map with my pin in the center – the other views such as Satellite work fine. Can you explain why this happens?

XHTML Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>