in All Posts, APIs/Mashups, Web

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.

Write a Comment

Comment

367 Comments

  1. Hi Tom. I’ve been trying to develop a map that A) lets the user first type in their postcode , then B) allows them to move/adjust the position of the marker. Before saving it all back to a database! I’m trying to use your code with this script — http://mytubestop.com/add_marker_test.php — but can’t seem to get it working, I don’t know what the heck I’m doing. So , I’ve put the script back to normal, without your code added and was jut wondering, if you could help me.

    If you can also tell me how to stop the user from adding multiple markers, I’d be really chuffed and would gladly give you a mention when my site is full off the ground. I can give you a sneak preview if you email me.

    Thanks
    Lee

  2. Oh yeah! I love it when I answer my own questions 🙂
    The Solution to my own problem is here: http://mytubestop.com/add_marker_test.php

    Firstly, I’ve made the function placeMarkerAtPoint() dragable. Then I had to add var point = marker.getPoint(); so that the new co-ordinates would be updated on dragend, which for effect I’ve added to the info window.

    Try it out. Put in a postcode, click Center Map then Place Marker. Then drag the marker to see the lat/lng variables update !!

  3. Google’s built in Geocoding may be “over a mile off on some postcodes” but yours is several thousand miles off for others. Newport NP1 for example.

  4. Tom,
    I am just getting started with Javascript and HTML so am on a steep learning curve. I have a map onto which I am loading a handful of post codes from a file. The file contains the post code and a description. I drop into a loop calling usePointFromPostcode for each post code and these come out on the map fine.

    I am stuck on adding the description to the marker using GMarker.bindInfoWindowHtml. How do I get the description for each post code through to the callback function so that it can add the description. I have tried a few things but the best I have achieved is for the description of the last post code to appear on all the markers.

  5. Hi!

    Thanks for guidance. Can some one guide me that how can all this be used in pure PHP. Like only the following URL

    ‘http://maps.google.com/maps/geo?output=csv&key=$api_key&q=’ is used to get CSV output from Google server for latitudes and longitudes.

  6. nice solution. i still cant find anything from royal mail and there price is too expensive that i cant afford.
    is there anything i can find for finding street name. like if i enter postcode and find the street address.

  7. hi, i have installed a property management app and need to import a UK postcode csv data file for the map and location finder to work. where can i get this from?

    please help with this. thanks for your time. tony

  8. Hi tom,

    Good article and your work is great. First of all thanks for that.

    But,
    I want to find the distance between two postal codes which are entered in a form with Two textbox.

    Waiting for you reply.
    Thanks

  9. Great article. Was wondering, if you overlay an image over an area of a map, is it possible to work out which towns, countries the overlayed image covers?

  10. Hi,

    I was having immense problems with gettin this to work, I kept getting the Glocalsearch not defined error. This is because you need version 2 of the maps JS and version 1.0 of the API JS. I just viewed the source of this page and copied and pasted the two Javascript references and changed the API keys and it all works fine now.

  11. The Data Mapping engine in Data Transformation Server allows any-to-any transformations between different data formats. It includes complex data functions such as string, math, and conditional operations as well as DB and XML file look-up.

  12. I’ve hard-coded the postcode in to my JavaScript function so it goes straight to that location on page load. But I have been unable to get the marker to be displayed upon page load – does anyone know how to do this?

  13. hi, great tutorial first of al!

    i just wondered if anyone could help me out on the terms side of things.

    say i have a company website which has a database of my clients inc their addresses and i used the google api / ajax to store the long/lat numbers of their addresses in my database that ive returned from querying the google api, does this mean im infringing googles terms & conditions?

    on first thought i dont see how you would be, as its not many calls which are made, only when a new client is added, we query google for their lat/long, store it for possible further use with a radius search.

    whats peoples view on this???

    tx :o)

  14. Thank you for posting this blog entry, Tom. I found it very useful, and have implemented a slightly adapted version of your map system on the My School Christmas Cards website.

    I have found a slight problem, though. The copyright notice at the bottom of the map can sometimes be too long for the map div to contain, and the notice spills out to the left. For example, try centring your map on the postcode SM7 2BQ. The copyright notice appears as follows: “Imagery ©2009 DigitalGlobe, Infoterra Ltd & Bluesky, GeoEye, Bluesky, The GeoInformation Group, Map data ©2009 Tele Atlas – Terms of Use”. In my browser, this stretches across your page margin, right over to the left-hand edge of the screen.

    The same happens on the website that I have implemented the system on, except that the notice actually interferes with text that I have on the left of the map.

    Is there any way around this?

  15. Oliver – the simple way to get around the copyright text spilling out of the map container is to add an extra CSS command to your map div.

    Just add ‘overflow:hidden’.

    It’s cheap and cheerful solution but seems to do the trick.

    Nick

  16. Hi,

    I have a table of UK postcodes stored in a MySQL database that I want to plot on a Google map.

    Does any one have any advice on how I could go about doing this? I have read through all the 100s of comments but can’t quite work it all out since everyone has slightly different requests.

    Thank you.

  17. Great tutorial.

    Just going through it now.

    Just one questions, I already have a Google Maps API key and have just got a Google AJAX API key

    However, looking at your code (demo page) the 2 keys you have are the same code?? Is it the GOogle Maps one or AJAX one?? Do I need the reference to both somewhere??

    Thanks

  18. Its OK, my mistake. Just generated another Google Maps API Key and its the same as the AJAX one

    Followed your instructions but not quite working. when enter location or postcode and press center map and place marker nothing happens.

    Ideally I want it to enter postcode, press button and it centres AND places marker on location

    Thanks

    PS – How do you get the “controls” to display – the zoom in and out etc

  19. I have a slight problem

    This is my code

    Search

    function CheckKey() {
    if (event.keyCode == 13) {

    usePointFromPostcode(document.getElementById(‘postcode’).value, showPointLatLng);
    }
    }

    If i enter a post code then click the search button everything is fine. But of I press the enter key which i have captured it goes to the function, but never actually does a new search and i just get the same results returned from the last search. Does anyone know why this could be happening. if i put an alert just before it calls localSearch.execute(postcode + “, UK”); then the alert will come up. As i said works OK on click but not on key down. Has anyone had a problem like this?

    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!”);
    }
    });
    alert(‘hello’)
    localSearch.execute(postcode + “, UK”);

    }

  20. Hi Tom
    What I need is the uk complete uk postal codes and the longditude
    & latitudes numbers to put into our site data base. I personal am not a web designer, so this is what I have been told that I need.
    Is this posible to get ?
    Vernon

  21. Hi Tom,

    This code has been a great tool for our site, however i am having issues with multiple calls the the usePointFromPostcode() function in IE although it works absolutly fine with Firefox. Could you please email me and i will give you access to our website and then we can talk about the issue here. We can also look at providing you some funding for any work you carry out for us.

    Thanks

    Scott

  22. i have done exactly as you have said … but for some reason i cant see the marker when i click on the buttons … i guess its not working properly … help is needed please. help as i need to integrate it in my classified adverts site.

    Cheers … hope it works out ..

  23. Wow this is great, its really what I was looking for.

    I have a slight problem though, on a basic HTML page the code workd fine but when I place it on an asp.net form I cant get it to work.

    I read further up the thread and tried what one user suggested, to put runat=server in the controls, i tried it in the input tag and the others too but still cant get it working.

    Any one cast any light?

    Thanks

    Tino

    aspx

  24. Would it be possible to provide an example using RESTful interface returning JSON object for ASP.NET C#?

    I belive it supports the GET method

    Regards

    Tino

  25. This is great. It also shows great weaknesses in my understanding of javascript.

    Try as I might, I can’t figure out how to make the system work off a postcode variable. As stated, onload doesnt work as a method to trigger the map to use a postcode. I cant find a place / modification which loads themap according to a postcode variable either.

    I am obviously being thick. Does anyone know/already have a variant of this code which works from a postcode variable passed to the code (or even a hardwired postcode rather than coords)?

    Many thanks if anyone can help with this, it is driving me mad…

  26. Thanks very much for this article Tom.. I have also made some additions to it like adding reverse geocoding.. getting address details from latitude and longitude.

    However, is there a possibility we can create a dll or a webservice that does that.. What i am trying to say since it uses Ajax/javascript that runs only on client side.. can we trick a page into thinking that it has been rendered on the browser to invoke the javascript..

    I have been trying to find a way to do that but have not been successful.

    Not sure if anyone else has tried it yet. if so do let me know..

  27. I am have a problem all to piont i put on the map have the same text can some see what i am doing wrong

    function usePointFromPostcode(postcode,ref) {
    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);

    var marker = new GMarker(point);

    GEvent.addListener(marker, “click”, function() {
    marker.openInfoWindowHtml(InfoText[ref]);
    });
    map.addOverlay(marker);
    }
    else {
    /* SKIP THAT PROPERTY CUZ I CAN’T FIND IT! */
    }
    });

    localSearch.execute(postcode + “, UK”);

    }

    function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != ‘function’) {
    window.onload = func;
    } else {
    window.onload = function() {
    oldonload();
    func();
    }
    }

    }

    function addUnLoadEvent(func) {
    var oldonunload = window.onunload;
    if (typeof window.onunload != ‘function’) {
    window.onunload = func;
    } else {
    window.onunload = function() {
    oldonunload();
    func();
    }
    }

    }

    addLoadEvent(mapLoad);
    addUnLoadEvent(GUnload);

    Welcome back Andrew here are you jobs for today

    var InfoText=new Array();
    InfoText[0] = ‘Job No. 3 Name : Price Phone ew’;alert(“0”);
    usePointFromPostcode(‘wa1 0py’, ‘0’);
    InfoText[1] = ‘Job No. 4 Name : 1 Phone 1’;alert(“1”);
    usePointFromPostcode(‘1’, ‘1’);
    InfoText[2] = ‘Job No. 4 Name : Tim Phone 1’;alert(“2”);
    usePointFromPostcode(‘WA4 0Py’, ‘2’);
    InfoText[3] = ‘Job No. 4 Name : a Phone 1’;alert(“3”);
    usePointFromPostcode(‘WA2 0PY’, ‘3’);
    InfoText[4] = ‘Job No. 4 Name : Price Phone ew’;alert(“4”);
    usePointFromPostcode(‘wa3 0py’, ‘4’);
    InfoText[5] = ‘Job No. 4 Name : price Phone 11’;alert(“5”);
    usePointFromPostcode(‘PO45 2ah’, ‘5’);
    InfoText[6] = ‘Job No. 4 Name : aa Phone 1’;alert(“6”);
    usePointFromPostcode(‘1’, ‘6’);
    InfoText[7] = ‘Job No. 4 Name : 1 Phone 1’;alert(“7”);
    usePointFromPostcode(‘WA2 0PY’, ‘7’);
    InfoText[8] = ‘Job No. 4 Name : 2 Phone 1’;alert(“8”);
    usePointFromPostcode(‘S70 4ST’, ‘8’);

  28. I had the same problem as Stew (June 7, 2007 @ 9:27 pm) and Matt (June 11, 2007 @ 4:20 pm)

    The page loaded with the buttons (map, satellite, hybrid, and the pan zoom buttons), but no actual map… just a blank white background.

    I even followed Tom’s advice and copied the the files from the demo page:
    http://www.tomanthony.co.uk/demo/geocode_uk_postcode/

    Still no joy.

    Then I noticed the htm file ends with
    <div id=”map”

    I replaced this with

    And bingo – it works.

  29. Sorry, code didn’t come out.

    I replace id=”map”

    with

    id=”map” style=”width: 700px; height: 450px”

    and this worked

  30. >>but no actual map… just a blank white background.

    the reason it comes out blank is because the map is styled [sized] in the css file, and by just copying the source you won’t have this styling info.

    the quickest way to remedy this to get the demo working locally is to just put the style inline in the head of your doc.

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

    hope that helps.

    rob ganly

  31. Got the code working no problem and thanks very much for providing.

    I am looking to embed the map into a PDF created from Coldfusion. When I add in the working code it produces nothin on the PDF.
    Anyone any ideas?

  32. I used your code a long time ago and has been working for well over a year but today it ha sstopped working and can see that the one on this site has stopped working too with the same errors fro JavaScript. Im gussing there will be a few people with this issue.

    Im currently looking for an answer and will post her eif I find something.

  33. A change must have been made with the API or a Windows update becase all the maps Ive looked at today that used this tutorial have now stopped working.

    Ive been trying to find an answer to no avail. The error is that the map doesnt display at all and you get some javascript errors referrign to localsearch and glocalsearch.

    Anyone with a fix it would be greatly appreciated.

Webmentions

  • Geocoding address before adding to database – PHP – CatchErrors June 15, 2009

    […] Check out http://www.tomanthony.co.uk/blog/geo…oogle-map-api/ […]

  • How to ensure the ‘correct’ variable is used in a loop with anonymous functions? | deepinphp.com June 15, 2009

    […] on March 19, 2011 by News We have followed Tom Anthony’s tutorial to calculate a geocode from a UK postcode to plot a marker on a Google Map. This has worked fine, […]

  • Bookmarks for June 8th from 11:12 to 11:38 « what i say // jon burger June 15, 2009

    […] Geocoding UK Postcodes with Google Map API | Tom Anthony – […]

  • interesting code snippets » Blog Archive » Geocoding UK Postcodes using PHP June 15, 2009

    […] Geocoding UK Postcodes with Google Map API […]

  • lookup reverse phone number June 15, 2009

    lookup reverse phone number…

    Which cell reverse phone lookup providers are you relying on? There are dozens of cell reverse services but you want to make sure you’re using the most accurate information available, right?…

  • links for 2007-09-03 June 15, 2009

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

  • 29 Coolest Custom Search Apps Built on Google June 15, 2009

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

  • existem.blog » Using the Google Maps API to add maps to your site June 15, 2009

    […] Please visit this tutorial by Tom Anthony which details how to do this. […]

  • 1000MileJourney » UK Geocoding in Rails June 15, 2009

    […] Tom Anthony’s has written an excellent article called Geocoding UK Postcodes with Google AJAX Search API. […]

  • Online Marketing Blog » Blog Archive » Geocoding Postcodes shouldn’t be hard… June 15, 2009

    […] Luckily there’s more than one way around the problem, and you can geocode postcodes for free (in one case using more than one Google API). Just look at the list of approaches and tutorials on Google’s own resource page for external geocoding tools. I rather like this method, as it’s relatively simple to code up… […]

  • Caching Google Maps Geocoder Results | Tom Anthony June 15, 2009

    […] After my post Geocoding UK Postcodes with Google Maps API I’ve had a few people contact me about caching geocoding results back to a server, for subsequent pages. […]

  • Devblog » Blog Archive » Postcodes to Google Maps on your website June 15, 2009

    […] Using the default Google Maps API you can only include maps based on longitude and latitude and not on a UK postcode. After a bit of searching I found a brilliant blog post on Tom Anthony’s site that shows you how to use a few JavaScript functions to center the map on a postcode and then place a marker there as well. After following the tutorial I got the map in place but I wanted to extend it so that as the page loads it automatically centers on the postcode and places the marker there. […]