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. Hello,
    Could you please provide me some guidance regarding how exactly link gets formed
    wen you enter any street address in the address bar of web browser?
    Does any API do this whole function of locating that place? Actually I am new to all these things, so I dont have much idea about this.

    Thank you.

  2. Hi Tom,

    I have found the tutorial to get the marker up very useful especially because I’m not a pro at javascript.

    This will give you an idea on what I’m up to.
    ‘http://mimtech.pepperio.net/contactus.html’

    However, I’m not able to get the FROM functionality on my site working.

    If you have a look at the URL above, you see a set of hard coded directions to my office. I’m trying to get this to look a bit more dynamic using a FROM – TO functionality of the maps. I have two options of design to do this:
    1. To have the map by default as it is just now when the page loads and then giving an option at the bottom to get the use to type in From and To. The submit resulting a list of directions.
    2. This option is to have the default map on loading of the page. Below the map there is a From input box. On submit it shows directions from the typed in Address / POSTCODE to my office (This is coded in the script).

    I would like to put more emphasis on the use of “PostCode” in the “From” field.

    Here is are some bits and pieces of the script:

    if (GBrowserIsCompatible())
    {
    var map = new GMap2(document.getElementById(“map”));
    var panel = document.getElementById(“panel”);
    var dir = new GDirections(map, panel);
    map.setCenter(new GLatLng(55.863741, -4.24171), 14);
    var marker = new GMarker(new GLatLng(55.863741, -4.24171));
    map.addOverlay(marker);
    var html=” ” +
    MIM Technologies Ltd” +
    “141 St James Road, G4 0LT” +
    “Tel: (0044) 0141 3038239”;
    marker.openInfoWindowHtml(html);
    map.addControl(new GSmallMapControl());
    }

    I have tried various other functions but had no success. Can you please help me with this? Any help is appreciated.

    Just to add that I’m using a CMS called Pepperio to do the website.

    Thanks!
    Chandra

  3. We’ve been giving this a go, but found there was a real lack of a decent free postcode finder in the UK in the first place – which we needed for some data in the first place. So we didn’t have much to work with.
    When our planned tool is complete we’ll post here again.

  4. Nice one!!
    Can we have some workaround to use this server side so that we can store the GECOCODES in storage file and then display the multiple address at same time on the map.

    e.g i have multiple office location in UK, and i need to show them at same time on map.

  5. Hi Tom,
    Can you suggest any of these third party services that you referred to?
    I have given my programmer your URL to take a look at your Google solution, but I would like a backup in case he sees a problem.

    Thanks,
    Robert

  6. Used this code for generating a map recently to show local stockists of a product. Have a database of postcodes to find the nearest 10 stockists, and then use their postcodes with this code to plot pins on the map.

    So using the AJAX function I just ran a loop for all 10 stockists. The pins are plotted fine. All brilliant!

    Then tested in the dreaded IE! Some of the bubbles had swapped marker. No idea why at all. I bodged a function to delay the loop for half a second before running the next postcode search and what do you know it works now.

    Any ideas?

  7. Thanks Tom – this has inspired me to add a new feature on a website. I would like users to submit a form to a php function that writes a postcode to a text file and then a point is display on a google map on another page. Can you possibly give me any ideas how this might be done.
    The idea is that people pledge to help with global warming and their pledge is marked on the map!

  8. Excellent & elegant example, thanks. This appears massively more accurate than Google’s much-vaunted “native” geo-coder. I wonder whether they’ve made it innacurate to keep the Royal Mail happy or something. Regardless, this is excellent, cheers again..

    Just need to code up a server-side version now 🙂

  9. Hi,

    First of all – thanks for this code – It *almost* does what I’m trying to achieve

    Basically, I want to use this – but actually pre-populate it, with a selection of Postcodes.

    I’ve tried adding this into the JS:

    localSearch.execute(“rh12 3he, UK”);
    localSearch.execute(“rh14 9jl, UK”);

    …but that doesn’t work.

    Anyone got any suggestions? Heres an example of what I’ve tried:

    http://www.gossamerlinks.com/testing_geo.html

    TIA!

    Andy

  10. Does this all mean that its possible to do this:

    Have a customer visit a web site and enter thier post code, then have google work out the distance from an office and send it back to the web site to see if they are too far away (say over 50Miles for example(?

    Because that would be very cool.

  11. Grewat code works well.

    My question is:

    I am looping through a database mapping the post codes, but I want to have an Information Window for each post code, how do I do this?

  12. Hi Anthony,

    I am looking for a way to find the postcode for a lat/long. Any ideas if i can acheive this and how?

    Many Thanks

  13. I would like to thank you for coming up with an genius bit of coding and sharing it with the rest of us, so that we may continue and build and adapt for our own applications.

  14. Hi, thanks for this post.

    This is much better than the Google geocoding API.

    The long and lat that are returned are far more acurate than just putting your postcode into the geocoding api.

    I will be using this technique on an estate agency website which I’m currently building.

    It will be going live at http://www.sellinghouses.co.uk next week some time (w/c June 16) in the mean time you can sneak a preview at http://www.thetaylors.eu/properties.asp

    Many thankd for the excellent post.

  15. Thanks Tom for a great tutorial in geo coding. I’ve successfully managed to incorporate it into my site, but now I have another (I hope simple) problem.

    Follow the link to view a property and you will see that the map tiles are not loading up correctly and the map page simply refuses to centre on the point. It always appears just off to the top left.
    Can anyone help?
    http://www.ukhousing.com/

  16. Thanks for the great tutorial, unfortunately it only encouraged me to continue down the blind alley of trying to achieve something similar to what Malcan was looking for back in April 2007.

    Eventually I looked around for another solution and what I couldn’t achieve after weeks of messing about with Google Maps was achieved with a solid afternoon’s work using Microsoft Virtual Earth. It’s slower and it’s Microsoft but it works! I just wish I could have achieved the same thing with Google Maps. http://www.anywherecouriers.co.uk/tariff1.html

  17. Hi,

    Sony : got the same problem a few days ago. It happens because you have your map loaded in an hidden div so the API cannot find your element’s width and height, thus it uses an element 0x0 and that’s the reason why it’s centered on the top-left corner. You can solve the problem by forcing the width and height in your function when you create your GMap2 object :

    new GMap2(container, {size:new GSize(width,height)});

    Hope it helps 🙂

  18. Hi

    Does anyone know how I can make this example query and load load automatically?

    I have the postcode already extracted from a database and just want the map to appear when a link is clicked.

    The link is someones name – when their name is clicked a php programme runs pulling their details and postcode from a db.

    I never use javascript so dont know how to automate js functions

    thanks
    Steve

  19. Just to clarify – the map is displaying with the default co-ordinates set up in gmap.js. I dont import gmap.js I have it as a js routine internally to allow me to populate my_postcode variable dynamically from php & database, but dont know how to get

    usePointFromPostcode(myPostcode, setCenterToPoint);

    to run automatically,

    Thanks
    Steve

  20. Hi,
    Can someone tell me how to I change the deafult map that I get in the sample code of google? I would like to have a map of the uk in my website.

    Thanks and regards,
    Gil

  21. Is it possible to do the reverse of this? I want to feed an address (either city, street, or even long/lat coordinates) and have Google report back a FULL UK postcode. Does this technique work around Royal Mail’s deathgrip on the copyright?

  22. Hi Tom
    I need u r help. I want to add google map in SEO. After finding my website this map should appear along with my keywords and web address. Please help me in this probelm.

  23. Hi Tom,

    I have been trying to implement your google maps api on a page load so that a postcode I have passed it displays in the map.

    Problem is I get an error saying the map object is not defined. I beleive this is down to a scope issue, but there is not in your example. So I am very confused as to why there is a problem when not calling it from a form.
    In firebug I get

    map is undefined
    [Break on this error] map.addOverlay(marker);

    Now what can I do to get this working?

    Thanks for submitting such good work open source, I really hope we can squash this bug and get it working for my application

    Thanks again

  24. Its not accurate. Both mine and my partners houses are approx 200 meters away according to your scripting, however if I use google directly its perfectly accurate.

  25. Tom whitbread said, September 2, 2008 @ 8:09 pm

    map is undefined
    [Break on this error] map.addOverlay(marker);

    I encountered this same problem. In my case it was beacuse i was calling the
    usePointFromPostcode(‘postcode’, placeMarkerAtPoint);
    in the body tag onload of the document. With gmap.js it checks to see if onload has been set to a function. however if you put the onload in the body tags then it the typeof is not a function and it runs
    window.onload = func;
    Which calls the mapLoad(). However this gets overridden by the body tags onload and so mapLoad() does not get called and doesnt get instatiated. That is why you get map is undefined.

    Basically you have to be careful where you call usePointFromPostcode from. You must make sure that mapLoad() gets called prior to usePointFromPostcode.

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

    addLoadEvent(mapLoad);
    in map.js

    and added in my code instead:

    window.onload = function() {
    mapLoad();
    usePointFromPostcode(‘postcode’, placeMarkerAtPoint);
    }

    as i say this only happens when there is a conflict of the onload is defined in the body tags, or if you do use window.onload = function() in your file to load other scripts you have to change in addLoadEvent

    else {
    window.onload = function() {
    oldonload();
    func();
    }
    }

    to

    else {
    window.onload = function() {
    func();
    oldonload();
    }
    }

    You see in the orginal script it calls your onload function first rather than the func() (which is the call to mapLoad() which initialise the map varibale) and so the map variable is not defined.

    I hope that clears things up….

    Eric
    caribbean diving holidays

  26. Excellent tutorial! One thing…. any way to stop the map bouncing you to San Francisco when you enter a random string (ie. not a UK postcode) into the search?? Getting this fixed would definitely stop the headaches!!

  27. Hi Tom,

    I’m a complete novice at this and I have some developers building a site for me. I wanted to contact you directly to ask you a few queries, but I couldn’t see any way to do this. Would this be ok?

    Tim

  28. Can anyone tell me if this solution is still accurate. I read that Google were downgrading the AJAX local search due to legal reasons and that it would therefore become less accurate.

    Is there any truth in this rumour?

  29. i’ve replicated the tutorial exactly but the map doesn’t get created? Has noone else had this problem? I think its to do with the onload business but i’ve tried several ways of calling mapLoad();

    It all seems so straight forward and its really frustrating that its just not working! Any help much appreciated!

    /// the error;

    GlocalSearch is not defined
    gmap.js()()gmap.js (line 2)
    [Break on this error] var localSearch = new GlocalSearch();

    ???

  30. Hi Tom, Your tutorial is exactly what i have been looking for in my Honours Project but unfortunatley I cant get it working, I dont even get an error to give me a clue, the map appears on the screen center to where I set but if i search the postcode the page refreshes and the textbox is emptied. Any ideas what could be the problem?

    Steven

  31. Dan – have you got both the Google header files included? One for maps and one for local search?

    Steven – In the spirit of ‘teach a man to fish’… Install the “Web Developer” Firefox extension and then try this. It has a popup box which provides Javascript errors and is exactly what you need for debugging problems like this. 🙂

  32. Yeah I have the web developer toolbar for firefox and unfortunatley for me it has found no errors with my code. I dont think its the syntax as I have copied your tutorial step for step, it’s not the keys either since i can see the map. the problem has me stumped lol

  33. Thanks tom, I finally got it, I have been developing this in asp.net and with a little trial and error I discovered I can wrap the map and its elements inside an element that has the attribute runat=server.

    Great tutorial. Helped alot.

    Any idea how to narrow the search to a particular house number?

    Steven

  34. Hi

    I have a quick query on Google Maps. Is the following statement correct, if so what is the solution to get around this? I.E. How do the likes of http://www.globrix.com/property/buy/edinburgh?ns=true&rd=1&br=buy&qt=edinburgh use googlemaps to plot the accurate placement of homes on the map?

    “Google is now capping the number of searches you can do using geocoding which is what is used to convert addresses to long/lat points on the map.

    They are doing this to force people to use the actual long/lat code when generating maps”

  35. Hi Tom,

    I have one query, there is a requirement to display the alternative of city will displayed suppose some one has entered elton as city name then api will display alternative of elton as ELTON- CHESTER- CHESHIRE,ELTON- LUDLOW- SHROPSHIRE,ELTON- MATLOCK- DERBYSHIRE. can we do this with use of this api.

Webmentions

  • Geocoding address before adding to database – PHP – CatchErrors November 10, 2008

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

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

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

  • interesting code snippets » Blog Archive » Geocoding UK Postcodes using PHP November 10, 2008

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

  • lookup reverse phone number November 10, 2008

    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 November 10, 2008

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

  • 29 Coolest Custom Search Apps Built on Google November 10, 2008

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

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

  • 1000MileJourney » UK Geocoding in Rails November 10, 2008

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

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

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

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