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

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

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

  4. 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 :'(.

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

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

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

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

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

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

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

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

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

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

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

  16. great post, will try and implement this.

  17. Very good post.

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

    Regards
    ravind

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

  19. Awesome stuff there Tom, I’m greatly appreciative!

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