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,

    Great information and tutorial.. I’m taking advantage of the help you’ve been giving people in the comments to see if I can pick your brains….
    I would like to implement a system where I can check if a route that someone enters on Google Maps passes a certain point (and judge proximity to that point).. I guess it could be done by getting the long/lat of each stage in the route directions and checking that against the point through a loop, but just wondered if there was already a function to check this? Any thoughts would be much appreciated..
    Regards..

  2. Hi.

    What does the line localSearch.execute(postcode + “, UK”); do?

    Hasn’t the point already been created by this stage?

    Thanks

  3. Chris, Google’s UK geocoding for addresses is pretty good but I found that it doesn’t work if the address you send it has a building name rather than a number. .e.g. “12 Smith Street, SomeTown, UK” works, but “Cherry Cottage, SomeTown, UK” does not.

    Google’s address geocoding can sometimes be more accurate than postcode geocoding. I’d say it’s 50/50 meaning that half the time Google’s address geocoding is better and vice versa. Tom’s technique is brilliant though and it will work every time, unlike Google’s address geocoding. The perfect solution is to use address geocoding and if you get an error from the result try again using postcode geocoding. For large buildings (office blocks, flats, etc) with their own unique postcode you will find that Tom’s postcode geocoding is always bang on the mark.

    Tom @ Fivebyte – I love your idea for getting users to update their coordinates using a draggable marker. I’m surprised no one has commented on your work (http://www.klubbedout.com/ajaxgeo.php) it’s really neat.

  4. My comment was deleted. Here goes again…
    Chris, Tom’s clever postcode geocoder is still very important because the official gmaps geocoder for addresses doesn’t work if the address you supply has a building name. It requires a building number which is fine for many residential addresses except some blocks of flats or “Cherry Cottage” etc. The accuracy of Google’s address geocoding is not that accurate surprisingly. e.g. my address is 20m out.
    Gary.

  5. Hi Tom/All,

    I have had the same problem as others with GlocalSearch not being set. I have noticed however that my url to Google AJAX Search API is pointing to v2 where as yours is pointing to v1. How can I get v1, or do you have a solution using this API?

  6. Tom, congratulations on this. I had a project that wnet on the back burner last year because there was no free way to convert postcodes to locations in the UK – now I can pick it up again 🙂

    @Tom and @Gary F: now there’s Google local search, Google Maps geocoding and Google Ajax Search, can you shed any light on the difference? I was surprised Tom’s example above didn’t geocode an address – I thought the Ajax search tool would do this? Is there a break-down anywhere of what each is capable of?

    Peter

  7. @Gary F: To clarify my question, you say “Google’s UK geocoding for addresses is pretty good but I found that it doesn’t work if the address you send it has a building name rather than a number.”

    What approach do you use for such buildings, if you don’t kow the postcode?

  8. Thanks – a great tutorial.

    Have you come across the little problem of the geocoder treating postcodes with “st”, “nd”, “rd” or “th” as if they are addresses with 1st, 2nd, 3rd, or 4th? Working this out now…
    Tim

  9. Set best view for markers Avatar
    Set best view for markers

    I have some markers on the map. I want to set best view for these markers (we can see all of these markers with the best view). Please show me the way to implement it.

    Thanks,

  10. Hi Expert

    can anybody give me code in server side scrtip like C# or vb.net

    Thanks in advance

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

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

  13. hi ,
    i am trying this code in asp.ner master pages.
    but its giving object not found error.

    can u hel me…??

    thanks

  14. Hi Tom,

    It seems to be a very good solution.

    I want to know whether we can use it in a similar manner to use zip codes for other countries like US etc.

    Thanks,
    Lisa

  15. Hello Tom,

    I was wondering if you could give some pointers on whether it is possible to get googlemaps to output a list of street names and generic postcode (eg: WC1 or NW2) within a given (user defined) distance based on a given postcode.

    can it be done?

  16. Hi Tom,

    I came across your blog while looking for a solution to a problem I am having with UK Geocoding. I had previously been using the GClientGeocoder from the google maps API to map UK postcodes.

    As of yesterday this was working great, however as of today it seems that google is no longer returning results for UK postcodes.

    I was just wandering if you were aware of this and if you knew anything about it?

  17. Hi, I found the same that map UK postcodes doesn’t work from yesterday, does anyone knows something about that, is that temporarily or …

    Regards,
    Emil Nenov

  18. I have a directory which gets the postcode from a querystring in .net and geocodes for UK this has also stopped working i keep getting Postcode not found?

  19. Hi everyone, I got the same problem, it’s seems like google has been changed something on their end, which always returning the post code not found