04 Mar 2007

By - 397 Comments

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:

[code]]czoyNjc6XCI8c2NyaXB0IHNyYz1cImh0dHA6Ly9tYXBzLmdvb2dsZS5jb20vbWFwcz9maWxlPWFwaSZ2PTIma2V5PSpLRVkqXCINCnR5cHtbJiomXX1lPVwidGV4dC9qYXZhc2NyaXB0XCI+PC9zY3JpcHQ+DQoNCjxzY3JpcHQgc3JjPVwiaHR0cDovL3d3dy5nb29nbGUuY29tL3Vkcy9hcGk/e1smKiZdfWZpbGU9dWRzLmpzJnY9MS4wJmtleT0qS0VZKlwiDQp0eXBlPVwidGV4dC9qYXZhc2NyaXB0XCI+PC9zY3JpcHQ+DQoNCjxzY3JpcHQgc3J7WyYqJl19Yz1cImdtYXAuanNcIiB0eXBlPVwidGV4dC9qYXZhc2NyaXB0XCI+PC9zY3JpcHQ+DQpcIjt7WyYqJl19[[/code]

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:

[code]]czozOTpcInZhciBsb2NhbFNlYXJjaCA9IG5ldyBHbG9jYWxTZWFyY2goKTsNClwiO3tbJiomXX0=[[/code]

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:

[code]]czo0NTY6XCJmdW5jdGlvbiB1c2VQb2ludEZyb21Qb3N0Y29kZShwb3N0Y29kZSwgY2FsbGJhY2tGdW5jdGlvbikgew0KCQ0KCWxvY2F7WyYqJl19bFNlYXJjaC5zZXRTZWFyY2hDb21wbGV0ZUNhbGxiYWNrKG51bGwsIA0KCQlmdW5jdGlvbigpIHsNCgkJCQ0KCQkJaWYgKGxvY2FsU3tbJiomXX1lYXJjaC5yZXN1bHRzWzBdKSB7CQkNCgkJCQl2YXIgcmVzdWx0TGF0ID0gbG9jYWxTZWFyY2gucmVzdWx0c1swXS5sYXQ7DQoJCQkJe1smKiZdfXZhciByZXN1bHRMbmcgPSBsb2NhbFNlYXJjaC5yZXN1bHRzWzBdLmxuZzsNCgkJCQl2YXIgcG9pbnQgPSBuZXcgR0xhdExuZyhyZXN7WyYqJl19dWx0TGF0LHJlc3VsdExuZyk7DQoJCQkJY2FsbGJhY2tGdW5jdGlvbihwb2ludCk7DQoJCQl9ZWxzZXsNCgkJCQlhbGVydChcIlBvc3R7WyYqJl19Y29kZSBub3QgZm91bmQhXCIpOw0KCQkJfQ0KCQl9KTsJDQoJCQ0KCWxvY2FsU2VhcmNoLmV4ZWN1dGUocG9zdGNvZGUgKyBcIiwgVUtcIntbJiomXX0pOw0KfQ0KXCI7e1smKiZdfQ==[[/code]

It takes 2 arguments; [code]]czo4OlwicG9zdGNvZGVcIjt7WyYqJl19[[/code] is the postcode you want to look for, and [code]]czoxNzpcIiBjYWxsYmFja0Z1bmN0aW9uXCI7e1smKiZdfQ==[[/code] 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 [code]]czo3OlwiR0xhdExuZ1wiO3tbJiomXX0=[[/code] (often just called a point); I’ve supplied 2 sample functions, [code]]czoxOTpcIiBwbGFjZU1hcmtlckF0UG9pbnRcIjt7WyYqJl19[[/code] and [code]]czoxNjpcInNldENlbnRlclRvUG9pbnRcIjt7WyYqJl19[[/code] 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:

[code]]czoyMDA6XCI8aW5wdXQgdHlwZT1cInRleHRcIiBpZD1cInBvc3Rjb2RlXCIgc2l6ZT1cIjEwXCIgLz4NCjxpbnB1dCB0eXBlPVwic3VibWl0XCIgdntbJiomXX1hbHVlPVwiUGxhY2UgTWFya2VyXCIgb25jbGljaz1cImphdmFzY3JpcHQ6DQp1c2VQb2ludEZyb21Qb3N0Y29kZShkb2N1bWVudC5nZXRFe1smKiZdfWxlbWVudEJ5SWQoXCdwb3N0Y29kZVwnKS52YWx1ZSwgcGxhY2VNYXJrZXJBdFBvaW50KVwiIC8+DQpcIjt7WyYqJl19[[/code]

We have a field for inputting a postcode, and I’ve added a button for placing a marker there. Where I have [code]]czoxODpcInBsYWNlTWFya2VyQXRQb2ludFwiO3tbJiomXX0=[[/code] you can put a reference to your own function, or you can even add a function right in there, like this:

[code]]czoyMzQ6XCIJPGlucHV0IHR5cGU9XCJzdWJtaXRcIiB2YWx1ZT1cIkRvIHdoYXRldmVyXCIgb25jbGljaz1cImphdmFzY3JpcHQ6DQoJdXNlUHtbJiomXX1vaW50RnJvbVBvc3Rjb2RlKGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKFwncG9zdGNvZGVcJykudmFsdWUsDQoJCWZ1bmN0aW9uIChwb2l7WyYqJl19bnQpIHsNCgkJCWFsZXJ0KFwnTGF0aXR1ZGU6IFwnICsgcG9pbnQubGF0KCkgKyBcJ1xcbkxvbmdpdHVkZTogXCcgKyBwb2ludC5sbmcoKSk7e1smKiZdfQ0KCQkJfSlcIiAvPg0KXCI7e1smKiZdfQ==[[/code]

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.

397 comments on “Geocoding UK Postcodes with Google Map API
  1. bill

    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

  2. Daybase

    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?

  3. Rich

    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 :’(.

  4. Rich

    My apologies, didn’t see the link :-s.

  5. Steve Smith

    HI, this looks great – can it be adapted for the Google Earth API?

  6. d jackson

    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

  7. Margaret

    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 ?

  8. Joel Cass

    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.

  9. Tom Cox

    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?

  10. brian

    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

  11. Andy

    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

  12. Darren

    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

  13. James

    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.

  14. Rob Baines

    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!

  15. Pawan

    great post, will try and implement this.

  16. ravindra

    Very good post.

    I want to display multiple locations on the map. How to do this? Please tell me

    Regards
    ravind

  17. Mazed

    Hi

    Thank you for your hard work – ive been looking for his for some time and i am very happy it works on my site. thanks

  18. ToughTomato Web Design

    Awesome stuff there Tom, I’m greatly appreciative!

  19. John Shearer

    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

  20. Tenax software developer

    Awesome script!
    Thanks for the help.
    If there is any way you can also extract address details?

  21. Andrew T

    Hi there

    Firstly, Thanks for the great and helpful article, and I’m not sure if this is already in the comments, but i’d like to contribute something back:

    You should change:
    [code]
    mapload();
    GUnload();
    [/code]
    to
    [code]
    mapload();
    $(window).unload( function () { GUnload(); } );
    [/code]
    because It will help plenty people trying to use this code:
    [code]
    GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml("Marker Wants to work");
    });
    [/code]
    which won’t work after GUnload(); is called. The GUnload() function removes all event handlers from the map.

    Description:
    Dismantles all registered event handlers in order to prevent memory leaks. Should be called as a handler for the unload event.

  22. John Benson

    Hi Tom

    Do you know whether there is any way with Google to get a more precise position on a road than you get from the postcode, e.g. W1T 1NJ give you a certain road, but 10 Rathbone Street, London W1T 1NJ is more accurate still?

    Would a database of all UK postcodes offer the same level of accuracy as your solution please Tom?

    Many thanks for all your help!!!!

  23. Victoria

    Hi,

    First of all, great code. Thanks for sharing.

    I need to put together a search/map on my site so that if I type in a postcode/geocode the nearest 10 landmarks in relation show up on the map.

    I would be storing the landmark data in a sql database and calling these from the map but so far I have not been able to find a solution.
    Is Geocoding the way to go for this?

    Thanks for your help.

  24. Mazed

    Ive have finaly found what i was looking for. this saves me time. i would like to thank you.

  25. Andrew Barront

    Google basis (free) does not provide address verification (Geocoding) as there is no UK postcode license.

    This means postcode searches are very in-accurate. The proximity search is very poor, even for town searches, often not recognising locations.

    This is why Google have a premier and a enterprise solution which still is more expensive and not as good as business mapping specialists like bIng and Via Michelin who also have API’s.

    As a free lance developer, so serious business would use Google as the system is weak and really provides a watered down solution.

  26. Andrew Barront

    The Google free (basic service) still does not provide address verification as the Geocoding from Google is still poor and will always be as they want to paid their paid services.

    Thus the accuracy is weak and often plotted way off from where the POI should be.

    For maximum accuracy and customisation, no serious business of developer would use Google long term, not when mapping specialists like Bing and ViaMichelin offer low cost solutions which are 100 times better !

  27. Kieran

    thanks, this has been so helpful. More accuracy!! Thanks again!

  28. Vivek Agrawal

    Hi Tom

    Thanks for the great article.

    Just to share that I want to use GeoCode only for getting the lat/long and feed it to the database table. Could you please guide me at how to use your code for this. Sorry to bother but its a matter of urgency. Would be grateful if you could please reply.

    Many Thanks

    Vivek

  29. Ben

    Has anyone migrated this to V3 of the Google Map API Javascript?

  30. John Issacs

    I am a web developer and had a 2 month project testing both solutions after reading the outcome of the IMFA regarding European business mapping providers.
    The wikipedia page for Google states it only provide BASIC Geocoding, so Kieran I agree with you on the accuracy point. The data cannot be cached. The V3 version has too many bugs still Ben.

    I noted that the free Google solution took twice as long to develop, had only basic Geocoding and everything else had to be developed from scratch I.e. criteria search, database management. Still Google business customers both paid (up to £7800) a year and free (if the solution will not be re sold (i.e. vehichle tracking) have no access to the UK postcode data from the royal mail as Google are no licensed (hence the often appalling accuracy) with only 4 digit postcode verification.

    In a positive, Google is a pretty basic platform and for the most part is free to use and widely available and recognised.

    The API platform from ViaMichelin (used a mixture of javascript skills) was offered to me on a free trial for 45 days and took only a few weeks to complete, Geocoding for address verification was included (so ideal for store finder, reserve and collect, etc and gave me access to live human support (to see what else I could do with their api). They provided me a platform with full Europe coverage and geocoded Ireland which Google could not offer for a price cheaper than the Google enterprise and premier.

    Bing fell behind when it came to customer support as it was non existent and the former multimap owned company owned by microsoft took just over the 2 months to get back to me.

    Like for like, The new ViaMichelin API solution wins, For a basic solution use Google, for business’s looking for real quality use Viamichelin

  31. Kaore

    Here is a short tutorial implementing geocoding and reverse geocoding on the client side: tech.cibul.org/geocode-with-google-maps-api-v3

  32. Kaore

    Here is a short tutorial implementing geocoding and reverse geocoding on the client side: http://tech.cibul.org/geocode-with-google-maps-api-v3

  33. Riz

    It is so great and easy. Thank you so much.

  34. Pony Express leicester

    has any body worked on coding from uk to the rest of europe with google maps?

  35. Jonas

    I stumpled upon this website: http://www.postcode-distance.com
    It does make the job for me. Ok it’s not free, but they supply me with updates…
    Maybe this is an alternative for professional projects that do not mind to semnd a few bucks…
    Hope that helped somebody…
    Anyway, thanks for the cool article…

  36. East London

    Thanks its a great help – thaks for writting the article brother

  37. vernon purcell

    We got 18 million postcode with L& A
    Thanks

  38. Nick Gornall

    many thanks for a great simple script. Now just need to work out how to add the listener to enable click of the marker with popup info.

    Thanks again!

  39. Scott

    Thats me got somthing for the weekend cheers

  40. Megha

    Its good to see that you have shared such a simple script. Hope it will help me to materialize my market plan.

  41. Nath

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

  42. Brian Jones

    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.

  43. Rob

    Thanks this tutorial is exactly what i needed thanks! I will be having a play later.

  44. Jr

    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.

  45. Mike

    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.

  46. Packaging

    Easily the best tutorial I’ve found for the Google Maps API – Thank you for the detailed information.

  47. neeraj sharma

    its very nice and really working good on my site

  48. Shriji Infotech

    thank you very much tom. really nice tutorial…

    very nice

  49. Marlon Naidoo

    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

  50. alan

    thankyou..perfect:)

Leave A Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>