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

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

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

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

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

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

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

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

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

  10. 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 πŸ™‚

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Webmentions

  • Geocoding address before adding to database – PHP – CatchErrors May 6, 2011

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

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

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

  • interesting code snippets » Blog Archive » Geocoding UK Postcodes using PHP May 6, 2011

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

  • lookup reverse phone number May 6, 2011

    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 May 6, 2011

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

  • 29 Coolest Custom Search Apps Built on Google May 6, 2011

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

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

  • 1000MileJourney » UK Geocoding in Rails May 6, 2011

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

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

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

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