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. Is the code still working properly? , I get US places appear on the map. Also words such as ‘nothing’ aren’t being returned as false. Thanks

  2. hemanth – It should work locally. Try using a few alert() statements to get feedback on what is going on. Try also making a demo of just the maps and just the local search (separate) so you can narrow down where the problem might be.

    Wilfred – Can you give me some example postcodes that show in the US?

  3. I don’t know if it’s a US postcode but if I enter ‘red’ it centres the map to location in what appears to be San Fransico.

  4. OK – but it is unlikely you ever need to geocode the word ‘red’. So I’m guessing you have a list of addresses that need to be geocoded and some don’t work?

  5. Thanks for this. It was perfect for what I needed to get me started pre-populating a form from a postcode. If anyone is interested head over to the google api docs to find out what else you can grab. Couldn’t get the street unfortunately, but this might be a Royal Mail licencing issue?

    Thanks again for the great bit of code to start me off.

  6. Anybody know (ping Tom :0) how to add a unique string + the postcode as a bubble mouseover on the marker?

    For some reason all of my markers get the last text string rather than a unique string per marker.

    Thanks

  7. Hi Tom,

    I don’t know if you’re notified about any new comments on this post, but… I looked into this stuff around a year ago and this article has kind of sparked my interest again. What I wondered (this was what I originally wanted to do), is can multiple postcodes be handled at the same time. For instance, could I return many postcodes as the result of a SQL query and have them all plotted at once on the map? I then planned to have them merge into clusters with total numbers as I zoom out… I’ve done an example of this with map clustering but it’s static, i.e. The pins are placed by me in the code, not dynamically assigned as a result of geocoding.

    Cheers mate,

    Chris

  8. I like it! Can the demo that you have easily be modified to paste in a list of postal codes to see multiple points on the map instead of typing in one by one? And increase / snap the map out to bigger size?

  9. I hope this isnt a silly question, but will this same tutorial work for Canada, which also uses post codes? I was thinking of implementing this on a local directory site of mine. Thanks

  10. Hi All,

    I recently started working on Google Geocoding API. When i am querying using API(HTTP request) getting less results(some times only one result).

    Example Http Request: http://maps.googleapis.com/maps/api/geocode/xml?address=icici, mumbai, india &sensor=false

    My client saying that, the other company guys are getting more results for the same address.

    Is there any seoperate API provided or is there any other way to do geocode?

    Note: The results getting for others are not equal to the resutls returning from the API. but those are equal to the results displaying in http://maps.google.co.in

    Any one please help me…

  11. Hi,

    I am looking for some way to do this in reverse ie if I know the Lat/Lon how could I query with a Google API to get the resulting Postcode for where I am?

    Does anyone have an idea of how this might be coded?

    Thanks

  12. trying to implement it on a different Web site. I thought I’d just need to generate a couple of new API keys, but the whole authentication system seems to have changed. Can someone advise me as to what I now should put in the code for loading the APIs (where previously one had the keys as parameters)?

  13. OK, let’s try again! I had this working fine a while ago, but now I’m trying to implement it on a different Web site. I thought I’d just need to generate a couple of new API keys, but the whole authentication system seems to have changed. Can someone advise me as to what I now should put in the code for loading the APIs (where previously one had the keys as parameters)?

  14. how to pass multiple postcodes using Javascript instead of single markers via input type? Driving me insane….

    Thanks

  15. Hello, Tom
    this code is working good but i need thing that automatically display street addresses as we entered postcode in text field,
    if you have any idea then please post here,
    Thank You

  16. Looks like Google have made some changes that has broken this. Geocoding no longer seems to be working on my site or yours.

  17. This code works this morning but when I try the postcode this afternoon, it always prints “Postcode not found”, I share the link to my friends and the result does not change. I don’t know why

Webmentions

  • How to ensure the ‘correct’ variable is used in a loop with anonymous functions? | deepinphp.com April 21, 2014

    […] 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 April 21, 2014

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

  • interesting code snippets » Blog Archive » Geocoding UK Postcodes using PHP April 21, 2014

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

  • lookup reverse phone number April 21, 2014

    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 April 21, 2014

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

  • 29 Coolest Custom Search Apps Built on Google April 21, 2014

    […] 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 April 21, 2014

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

  • 1000MileJourney » UK Geocoding in Rails April 21, 2014

    […] 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… April 21, 2014

    […] 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 April 21, 2014

    […] 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 April 21, 2014

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