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,

    2 qestions – there still appears to be a minor ‘innacuracy’ with the pinpoint locations for UK postcodes (e.g. if I enter a known address I can see that the marker is 100 yards down the road from where it should be…

    and secondly.. the map always opens up in ‘satellite mode’ – how do i set this so it always goes to ‘map’ view?

    regards

    Maxine

  2. Thanks dude, I must say you saved my day. I’ve been struggling with UK geocoding but never got a way around it. This solution made more sense than any other solution (obviously a free one).

    Cheers,

    Avy

  3. scott —

    Take a look at the post following this one – it explains exactly what you are after! 🙂

    Maxine —

    Remember this is using postcode only, not a complete address. Postcodes aren’t unique to a single address, but cover a number of addresses. This is the ‘innacuracy’ you are seeing.

    As for changing the view being used, in the mapLoad() function see this line:

    map.setCenter(new GLatLng(54.622978,-2.592773), 5, G_HYBRID_MAP);

    You can change G_HYBRID_MAP to G_NORMAL_MAP or G_SATELLITE_MAP depending what you want. 🙂

    Avy —

    You are welcome. 🙂

  4. Thanks a lot, you’ve saved my time 🙂

  5. hi,

    i am using the same script what you gave below and grap the key using above mentioned url.but it shows the ‘Glocalsearch is undefined’ please help me

    this is my key

    I am not passing any extra argument to this function
    function usePointFromPostcode(postcode, callbackFunction)

    Please help me
    Thanks
    mani

  6. Hi,

    I am real problems gettin this to work

    I tried the soucre from this page http://www.pets4homes.co.uk/pets4homes/home.nsf/TestMap?openForm&PostCode=bb24jh
    and it works fine so I guess my keys/webspace etc are ok

    All I get when I try Toms code is buttons but no map?

    Any help would be great.

    Thanks

  7. Hi,

    I’m having the same problem as above. The page loads with the buttons (map, satellite, hybrid, and the pan zoom buttons), but no actual map… just a blank white background.

  8. mani – have you included both the script tags for Google at the top of your page?

    Stew, Matt — either of you have an example URL you can post or email to me?

    Have you tried copying the files from the demo page:

    http://www.tomanthony.co.uk/demo/geocode_uk_postcode/

  9. Anyone know whether it’s possible to do the reverse of what’s been discussed above – notably click on the map and get a UK postcode back for this location?

    Given there are lots of people who don’t know their postcode and far more who want to use tools that are driven by postcodes but don’t know them for abitrary areas, I consider this is just as vital.

    Apologies if this has been discussed before – am new to this

    Thanks.
    KD

  10. Thanks excellent info. only problem I had was not being able to display the maps correctly but as soon as I realized I needed a styles.css and nofollow.css document worked like a charm.

    I am trying to setup the following option, when somebody clicks on a name of a town or village a map is displayed? Unsure how to go about this?? anybody have any ideas or does somebody want to earn some money setting up a script etc for me????
    help (at) onefix.co.uk

    thanks again seems very accurate postcode finder for postcodes I have tried

  11. Was thinking about adding this feature for some time but thought it was to much grief up until now.
    This is a great piece of work.
    Thanks for the time and effort you put into this Tom.

    I followed the above guide and it was working on first go, brilliant.

    I do have one query however.
    If i already have the postcodes and they are being passed to the page via php where would i put these so i could do away with the input fields ? i could echo them into a hidden field or something. but im not sure how to pass the postcode to the gmap.js.

    I will figure it out soon. Its a great piece of work. thanks Ian.

  12. Hi Tom

    Great tutorial!

    As UK postcodes aren’t totally accurate for pinpointing a specific building, I have made a modification to allow draggable markers. A listener will then output the new lat and lng to a form field.

    http://www.klubbedout.com/ajaxgeo.php

    However, once a marker is moved the map won’t re-centre on the new point, the lat and lng (when clicking on show lat/lng) is still the one from the original lookup, also my form field isn’t filled until the marker is dragged.

    Can you offer any assistance?

    🙂

  13. Hi Tom,

    A couple of issues I can see:

    – You allow multiple markers, so if I am centering the map, which marker should I use?

    – The center map button still calls usePointFromPostcode(), so it ignores your updates completely. What you need is a wrapper function on the button, so if there is no marker, it calls usePointFromPostcode() as before, but if there is a marker, it centers there instead.

    I hope this gives you a nudge in the right direction. 🙂

  14. Hi Tom,

    I have followed your tutorial, its gr8. but i couldnt see the Map over there. i have place two Keys and added the GMAP.js in the same path. but i couldnt see the Map as out put. Please have a look and let me know what happened.. Its really URGENT for me.. Please help me Tom.

    THanks a lot.
    Kiran

  15. Hi Tom
    Excellent tutorial. I have teh same problem as other ie I’m having the same problem as above. The page loads with the buttons (map, satellite, hybrid, and the pan zoom buttons), but no actual map… just a blank white background.

    I’ve used your sample .js file and input form and an API key that works on other files in the directory

    Any help welcome

  16. Kiran –

    In your html, where you include the map, you are missing an important section of the URL:

    http://maps.google.com/maps?file=api&v=2&key=……..

    I think that should solve your problem.

    S K –

    You haven’t copied the styles.css file from the demo page, your map element has not height and width set, you need this CSS:

    
    #map
    {
      height: 500px;
      width: 500px;
    }
    

    🙂

  17. Tom
    I gave you the wrong URL. The issue was simply failing to include the styles.css file. Do you know how to set up a facility to click on the map and return the lat, long co-ords.

  18. Hi Tom,

    I have updated file, according to your suggestions but the same effect. It couldnt solve the issue. Could you please look into and letme know..

    Thanks in advance
    Kiran

  19. Hey Tom,

    Sorry for the Previous Post, It solved my issue.. Thank you so much TOM.

    Kiran