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. Awesome script!
    Thanks for the help.
    If there is any way you can also extract address details?

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

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

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

  5. Ive have finaly found what i was looking for. this saves me time. i would like to thank you.

  6. Andrew Barront Avatar

    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.

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

  8. thanks, this has been so helpful. More accuracy!! Thanks again!

  9. Vivek  Agrawal Avatar

    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

  10. Has anyone migrated this to V3 of the Google Map API Javascript?

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

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

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

  14. It is so great and easy. Thank you so much.

  15. has any body worked on coding from uk to the rest of europe with google maps?

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

  17. Thanks its a great help – thaks for writting the article brother

  18. We got 18 million postcode with L& A
    Thanks

  19. many thanks for a great simple script. Now just need to work out how to add the listener to enable click of the marker with popup info.

    Thanks again!

  20. Thats me got somthing for the weekend cheers