in All Posts, APIs/Mashups, Web

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.

Write a Comment

Comment

367 Comments

  1. 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

  2. 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.

  3. 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?

  4. 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

  5. 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!

  6. 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?

  7. 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.

  8. 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

  9. 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.

  10. 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.

  11. 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!

  12. 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.

  13. 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

  14. 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.

  15. 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?

  16. 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..

  17. 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?

  18. hi there,
    can u do search on city name not on post code? actually i m developing a estate agent’s web site and my requirment is a user can search on city name or on post code if he knows.
    waitng….

    regards

    bill

  19. I have a map plotting various points from lon lat values on xml file. coordinates are for partial postcodes only eg M34 or SK5 – works great but accuracy so so. xml file also contains postcodes so how would I adapt to geode from the postcode. My code so far

    ……. GDownloadUrl(“mapdata.xml”, function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName(“marker”);
    for (var i = 0; i < markers.length; i++) {
    var name = markers[i].getAttribute(“name”);
    var address = markers[i].getAttribute(“address”);
    var mcol = markers[i].getAttribute(“mColor”);
    var pcode = markers[i].getAttribute(“pCode”);
    pcode=pcode.replace(“-“,” “);

    so at this point I have my postcode – where do I go from here please?

  20. The end result is brilliant compared to some of the articles out there, one question, it’s probably just me being stupid, but where do you get the includes like gmap.js? Can’t find them anywhere :'(.

  21. hi tom

    great script – i have it working fine – the only thing i cant get to work is to get the place markers to appear on the first page load – eg: so you dont have to press the Place Marker button

    i have tried various things to acheieve this – the most obvious being hardcoding the postcode and adding:

    i even tried adding a :

    addLoadEvent(usePointFromPostcode(‘CA11LE’, placeMarkerAtPoint));

    to the gmap.js

    but i just cant get the Place Marker to appear on the map when the page initially loads

    is it possibly not possible?

    many thanks

    djax

  22. Hi wonde r if you can help I need to have a excel spread sheet of Long lat and postcode to suffix level . do you know where I would get this ?

  23. Hi Tom,

    I guess this was written a couple of years back – it seems things have changed now, the geocoder seems to return the same point data that the local search API does.

    E.g. Try entering “”E95AG, UK” into the geocoder getLatLng method and it will return the same point as per the localsearch setSearchCompleteCallback method.

  24. Hi Tom

    Probably a daft question, I like how you can fetch the long and lats in display this as an alert. Although is their anyway they can be shown in two seperate textboxs one for lat and one for long?

  25. Hi Tom,
    Getting an error …
    Line: 2
    Error: ‘GlocalSearch’ is undefined

    I have read through the comments above and thought it might be the .css file so I moved that into my folder but that didn’t work.

    Any thoughts as to why the map is not showing?

    Thanks

    Brian

  26. Hi Tom

    I was wondering if you could point me in the right direction..

    your code is great but I need to use it in a differnt way. What I’m doing is performing a search for locations in a database that match the area the user enters – so I am extracting a post code for each location from my database then running your code as below several times (once for each maker I want) prior to the body tag being closed.

    usePointFromPostcode(‘M33 3DA’, placeMarkerAtPoint);

    The problem seems to be that the map isn’t displayed and the markers aren’t added – I’m confused…

    You can see it here http://sayers.tlatest.co.uk

    Any help you can give would be great…

    Thanks

    Andy

  27. This tutorial is great. I need to take it further I would like the user to select a postcode from a pick up point and a postcode to a destination and then to calculate mileage. Are there any tutorials that can show me how to do this? Thanks

  28. Hi,

    Indeed a very great tutorial!

    Just wondering if i could get additional help.

    Now i want to see the possibility of the lat and long generated to be stored automatically in my database. I know this has to do with defining a function to do the above. But, sorry very new to scripting!

    Any help would be greatly appreciated.

    Thank you.

    James.

  29. Great post, exactly what I was looking for. When will the post office ever give up milking their postcode database?

    Had it working in minutes. What foxed me was my page will doing postbacks for each click then I spotted all the buttons were type “submit” not “button” , doh!

  30. Hi
    Would you have a version of your postcode thing that outputs multiple postcodes
    I’ve got a thing i’m working on which you can see which puts multiple markers on a page a varies the type of marker depending on what the marker is eg hotel restaurant.
    Unfortunately it works using the lat & long in the database not postcode
    Any help much appreciated
    john shearer

Webmentions

  • Geocoding address before adding to database – PHP – CatchErrors March 23, 2010

    […] Check out http://www.tomanthony.co.uk/blog/geo…oogle-map-api/ […]

  • How to ensure the ‘correct’ variable is used in a loop with anonymous functions? | deepinphp.com March 23, 2010

    […] 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, […]

  • Bookmarks for June 8th from 11:12 to 11:38 « what i say // jon burger March 23, 2010

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

  • interesting code snippets » Blog Archive » Geocoding UK Postcodes using PHP March 23, 2010

    […] Geocoding UK Postcodes with Google Map API […]

  • lookup reverse phone number March 23, 2010

    lookup reverse phone number…

    Which cell reverse phone lookup providers are you relying on? There are dozens of cell reverse services but you want to make sure you’re using the most accurate information available, right?…

  • links for 2007-09-03 March 23, 2010

    […] Geocoding UK Postcodes with Google Map API | Tom Anthony (tags: geocoding googlemaps) […]

  • 29 Coolest Custom Search Apps Built on Google March 23, 2010

    […] Geocoding UK Postcodes – Step by step instructions for using the Google AJAX Search API to geocode UK postcodes so you can create Google Maps displays. […]

  • existem.blog » Using the Google Maps API to add maps to your site March 23, 2010

    […] Please visit this tutorial by Tom Anthony which details how to do this. […]

  • 1000MileJourney » UK Geocoding in Rails March 23, 2010

    […] Tom Anthony’s has written an excellent article called Geocoding UK Postcodes with Google AJAX Search API. […]

  • Online Marketing Blog » Blog Archive » Geocoding Postcodes shouldn’t be hard… March 23, 2010

    […] Luckily there’s more than one way around the problem, and you can geocode postcodes for free (in one case using more than one Google API). Just look at the list of approaches and tutorials on Google’s own resource page for external geocoding tools. I rather like this method, as it’s relatively simple to code up… […]

  • Caching Google Maps Geocoder Results | Tom Anthony March 23, 2010

    […] After my post Geocoding UK Postcodes with Google Maps API I’ve had a few people contact me about caching geocoding results back to a server, for subsequent pages. […]

  • Devblog » Blog Archive » Postcodes to Google Maps on your website March 23, 2010

    […] Using the default Google Maps API you can only include maps based on longitude and latitude and not on a UK postcode. After a bit of searching I found a brilliant blog post on Tom Anthony’s site that shows you how to use a few JavaScript functions to center the map on a postcode and then place a marker there as well. After following the tutorial I got the map in place but I wanted to extend it so that as the page loads it automatically centers on the postcode and places the marker there. […]