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
    Could you show us the inline code (for php) required to implement the functionality to return glat/glon? Google seem to have withdrawn the http request method for quick postcode to glat/glon functionality.
    Many thanks!

  2. Hi Tom,

    Excellent tutorial, Just wondering if there is any way you can also extract address details? for instance is it possible to;

    Enter Uk Postcode->Get the Geocode Coordinates-> use the coordinates to get address details…such as town/County and street if possible?

  3. I have just found you can get some address details using:

    var town = localSearch.results[i].streetAddress;
    var city = localSearch.results[i].city;
    var region = localSearch.results[i].region;

    Now the UK postcode geocoding has been stopped i have come back to this to pick them up 😉

  4. You’ve probably noticed that Google Maps have withdrawn their geocoding service for the UK now (within the last week or so).

    I have a CSV file containing a complete list of UK postcodes, along with lat/long – around 2.5 million entries in total – if anyone’s interested: http://linuxbox.co.uk/postcode_database.php

  5. Hi all,

    Can anyone tell me how I can use this code to generate directions from a point already marked on the map. I want to be able to have people put their postcode into a box and get directions to the church and hotel for my wedding. Ideally I’d like to be able to have them put their postcode in and then it gives directios to the church then to the hotel in one list. It used to work before Google took away the postcode function. Here’s a link: http://www.moatway.force9.co.uk/budget.html
    Thanks in advance.

    Dan

  6. Hi all,

    We are working on mashing up GoogleMap API in one of my project. We are finding difficulties in getting the correct location(lat & long) for UK postcodes. There is a significant difference with the Lat /Lng what I get from Geocoder and the one which I get from Isharemaps. For some of the codes, it is unimaginable. Is there any way to get correct lat & Lng through Geocoders with some Degree corrections on the latitude & Longtitude. Also I am looking @ a webservice instead of maintaining the whole database with me.

    I found an article which tells me on getting the Correct Lat & Lng with some delta error corrections. But of late, couldnt find that article.

    Pls suggest as I am in the middle of this project.

  7. Hi Tom, and all

    I am using a db query to return a postcode.

    The usePointFromPostcode function works to place the marker in the correct place, but the map.setcenter just does not work for me.

    map.setCenter(new GLatLng(54.622978,-2.592773), 14);
    which obviously is Tom’s default setting (which works) – but how do I center the map around the marker?

    I try map.setCenter(new GLatLng(point), 14);
    map.setCenter(new GLatLng(marker), 14);
    map.setCenter(point, 14);
    map.setCenter(marker, 14);
    map.setCenter(new GLatLng(resultLat, resultLng), 14);

    but nothing works… any ideas?

    Thanks

    Dave

  8. The statement

    Jack wang said,
    November 21, 2007 @ 8:08 am

    To CEO: Brand name of tomanthony
    Dear CEO,
    We are Shanghai Ujane Information Technology Co., Ltd, a domain name register organization in China. We have something urgent to confirm with your company. Because we formally received an application from a company named Lexiao (Hongkong) Investment company. …

    This is a scam.

  9. Nice Example liked it….!

  10. One of the best tutorials I’ve ever read

    Many thanks!

  11. Hi,
    I have just started using the API to pinpoint locations in the local area. I am using the GClientGeocoder() class in order to pin point addresses using the uk postcode. All works fine apart from when I use the point() returned by the getLatLng() method to setCenter() the marker on the map is located at the top left of the map control!! I have tried to center using the GetLatLngBounds() but it still remains in the top left corner of the control.

    Any help would be appreciated.

    Colin

  12. Thanks for this Tom – I’d found the geocoding included in the API to be a bit unreliable for UK postcodes. This solution however is spot on!

  13. Great tutorial. I’ll be using it on a forthcoming site. Many thanks.

  14. That’s great example. I think we can also use web API provided at geonames.org. I seen using it on http://postalcode.globefeed.com/UK_Postal_Code.asp

  15. Very nice found you on google and answered exactly what I wanted to know. Many thanks.

  16. Anshumaan Bakshi Avatar

    Nice script……..it really works.

    Thanks for the help

    AB

  17. Thanks..

  18. Just what I’ve been looking for,
    Thanks for the effort.

  19. Fantastic brilliant solution

  20. Hi there, I am making a property website and want to add this in my website. When user click on some property details it should show map with that property postcode. How can i pass postcode using php and fit in this script. thanks