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.

378 responses to “Geocoding UK Postcodes with Google Map API”

  1. Hi,

    I have a table of UK postcodes stored in a MySQL database that I want to plot on a Google map.

    Does any one have any advice on how I could go about doing this? I have read through all the 100s of comments but can’t quite work it all out since everyone has slightly different requests.

    Thank you.

  2. NickC – Thanks for the tip! That does indeed stop the text from spilling out.

  3. Great tutorial.

    Just going through it now.

    Just one questions, I already have a Google Maps API key and have just got a Google AJAX API key

    However, looking at your code (demo page) the 2 keys you have are the same code?? Is it the GOogle Maps one or AJAX one?? Do I need the reference to both somewhere??

    Thanks

  4. Its OK, my mistake. Just generated another Google Maps API Key and its the same as the AJAX one

    Followed your instructions but not quite working. when enter location or postcode and press center map and place marker nothing happens.

    Ideally I want it to enter postcode, press button and it centres AND places marker on location

    Thanks

    PS – How do you get the “controls” to display – the zoom in and out etc

  5. I have a slight problem

    This is my code

    Search

    function CheckKey() {
    if (event.keyCode == 13) {

    usePointFromPostcode(document.getElementById(‘postcode’).value, showPointLatLng);
    }
    }

    If i enter a post code then click the search button everything is fine. But of I press the enter key which i have captured it goes to the function, but never actually does a new search and i just get the same results returned from the last search. Does anyone know why this could be happening. if i put an alert just before it calls localSearch.execute(postcode + “, UK”); then the alert will come up. As i said works OK on click but not on key down. Has anyone had a problem like this?

    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!”);
    }
    });
    alert(‘hello’)
    localSearch.execute(postcode + “, UK”);

    }

  6. Hi Tom
    What I need is the uk complete uk postal codes and the longditude
    & latitudes numbers to put into our site data base. I personal am not a web designer, so this is what I have been told that I need.
    Is this posible to get ?
    Vernon

  7. Hi Tom,

    This code has been a great tool for our site, however i am having issues with multiple calls the the usePointFromPostcode() function in IE although it works absolutly fine with Firefox. Could you please email me and i will give you access to our website and then we can talk about the issue here. We can also look at providing you some funding for any work you carry out for us.

    Thanks

    Scott

  8. Thanks a lot for this, a legendary bit of work. Added a tag for django template language at: http://www.djangosnippets.org/snippets/1336/

  9. This is an excellent soltion

  10. i have done exactly as you have said … but for some reason i cant see the marker when i click on the buttons … i guess its not working properly … help is needed please. help as i need to integrate it in my classified adverts site.

    Cheers … hope it works out ..

  11. For anyway who is a novice like me and need the exact code to have your map load from a postcode stored in session variable – have a look at this link.

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

    Absolutely fantastic post by the way, been looking to do this for a long time now

  12. Might be useful to some to know that Google now has a RESTful interface to their AJAX Search API: http://code.google.com/apis/ajaxsearch/documentation/#fonje

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

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

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

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

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

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

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

  20. Hi, thanks for Great tutorial.