04 Mar 2007

By - 397 Comments

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:

[code]]czoyNjc6XCI8c2NyaXB0IHNyYz1cImh0dHA6Ly9tYXBzLmdvb2dsZS5jb20vbWFwcz9maWxlPWFwaSZ2PTIma2V5PSpLRVkqXCINCnR5cHtbJiomXX1lPVwidGV4dC9qYXZhc2NyaXB0XCI+PC9zY3JpcHQ+DQoNCjxzY3JpcHQgc3JjPVwiaHR0cDovL3d3dy5nb29nbGUuY29tL3Vkcy9hcGk/e1smKiZdfWZpbGU9dWRzLmpzJnY9MS4wJmtleT0qS0VZKlwiDQp0eXBlPVwidGV4dC9qYXZhc2NyaXB0XCI+PC9zY3JpcHQ+DQoNCjxzY3JpcHQgc3J7WyYqJl19Yz1cImdtYXAuanNcIiB0eXBlPVwidGV4dC9qYXZhc2NyaXB0XCI+PC9zY3JpcHQ+DQpcIjt7WyYqJl19[[/code]

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:

[code]]czozOTpcInZhciBsb2NhbFNlYXJjaCA9IG5ldyBHbG9jYWxTZWFyY2goKTsNClwiO3tbJiomXX0=[[/code]

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:

[code]]czo0NTY6XCJmdW5jdGlvbiB1c2VQb2ludEZyb21Qb3N0Y29kZShwb3N0Y29kZSwgY2FsbGJhY2tGdW5jdGlvbikgew0KCQ0KCWxvY2F7WyYqJl19bFNlYXJjaC5zZXRTZWFyY2hDb21wbGV0ZUNhbGxiYWNrKG51bGwsIA0KCQlmdW5jdGlvbigpIHsNCgkJCQ0KCQkJaWYgKGxvY2FsU3tbJiomXX1lYXJjaC5yZXN1bHRzWzBdKSB7CQkNCgkJCQl2YXIgcmVzdWx0TGF0ID0gbG9jYWxTZWFyY2gucmVzdWx0c1swXS5sYXQ7DQoJCQkJe1smKiZdfXZhciByZXN1bHRMbmcgPSBsb2NhbFNlYXJjaC5yZXN1bHRzWzBdLmxuZzsNCgkJCQl2YXIgcG9pbnQgPSBuZXcgR0xhdExuZyhyZXN7WyYqJl19dWx0TGF0LHJlc3VsdExuZyk7DQoJCQkJY2FsbGJhY2tGdW5jdGlvbihwb2ludCk7DQoJCQl9ZWxzZXsNCgkJCQlhbGVydChcIlBvc3R7WyYqJl19Y29kZSBub3QgZm91bmQhXCIpOw0KCQkJfQ0KCQl9KTsJDQoJCQ0KCWxvY2FsU2VhcmNoLmV4ZWN1dGUocG9zdGNvZGUgKyBcIiwgVUtcIntbJiomXX0pOw0KfQ0KXCI7e1smKiZdfQ==[[/code]

It takes 2 arguments; [code]]czo4OlwicG9zdGNvZGVcIjt7WyYqJl19[[/code] is the postcode you want to look for, and [code]]czoxNzpcIiBjYWxsYmFja0Z1bmN0aW9uXCI7e1smKiZdfQ==[[/code] 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 [code]]czo3OlwiR0xhdExuZ1wiO3tbJiomXX0=[[/code] (often just called a point); I’ve supplied 2 sample functions, [code]]czoxOTpcIiBwbGFjZU1hcmtlckF0UG9pbnRcIjt7WyYqJl19[[/code] and [code]]czoxNjpcInNldENlbnRlclRvUG9pbnRcIjt7WyYqJl19[[/code] 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:

[code]]czoyMDA6XCI8aW5wdXQgdHlwZT1cInRleHRcIiBpZD1cInBvc3Rjb2RlXCIgc2l6ZT1cIjEwXCIgLz4NCjxpbnB1dCB0eXBlPVwic3VibWl0XCIgdntbJiomXX1hbHVlPVwiUGxhY2UgTWFya2VyXCIgb25jbGljaz1cImphdmFzY3JpcHQ6DQp1c2VQb2ludEZyb21Qb3N0Y29kZShkb2N1bWVudC5nZXRFe1smKiZdfWxlbWVudEJ5SWQoXCdwb3N0Y29kZVwnKS52YWx1ZSwgcGxhY2VNYXJrZXJBdFBvaW50KVwiIC8+DQpcIjt7WyYqJl19[[/code]

We have a field for inputting a postcode, and I’ve added a button for placing a marker there. Where I have [code]]czoxODpcInBsYWNlTWFya2VyQXRQb2ludFwiO3tbJiomXX0=[[/code] you can put a reference to your own function, or you can even add a function right in there, like this:

[code]]czoyMzQ6XCIJPGlucHV0IHR5cGU9XCJzdWJtaXRcIiB2YWx1ZT1cIkRvIHdoYXRldmVyXCIgb25jbGljaz1cImphdmFzY3JpcHQ6DQoJdXNlUHtbJiomXX1vaW50RnJvbVBvc3Rjb2RlKGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKFwncG9zdGNvZGVcJykudmFsdWUsDQoJCWZ1bmN0aW9uIChwb2l7WyYqJl19bnQpIHsNCgkJCWFsZXJ0KFwnTGF0aXR1ZGU6IFwnICsgcG9pbnQubGF0KCkgKyBcJ1xcbkxvbmdpdHVkZTogXCcgKyBwb2ludC5sbmcoKSk7e1smKiZdfQ0KCQkJfSlcIiAvPg0KXCI7e1smKiZdfQ==[[/code]

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.

397 comments on “Geocoding UK Postcodes with Google Map API
  1. Will Postlethwaite

    Hi Tom great tutorial works great….. But only on one computer, works great on my macbook in which i developed it on) but not on my imac on the same internet connection.

    if you have any thoughts is would be amazing – please help!

    its displays the

    “This web site needs a different Google Maps API key. A new key can be generated at http://code.google.com/apis/maps/signup.html.”

    which i have seen others are getting but not working at all, I can get it to work on one but no other and I cant figure out why.

    I am testing this on the link below

    http://www.grenergysolar.com/map-stage1.html

  2. Will Postlethwaite

    Hi Tom great tutorial the best google api tutorial out there in fact, but….. i am having a slight problem, it works fine on the computer i built it on but on other computers it displays a messages saying i need to generate a new key, i think it might be some sort of permissions issue as it works fine on my computer. i have tested this on 3 other computers and the same massage id displayed

    I am testing it on the link below

    http://www.grenergysolar.com/map-stage1.html

    any assistance would be much appreciated

  3. Tom

    Hi everyone! Thanks for all the feedback, and sorry to those who have asked questions that have gone unanswered. I’ve been so busy doing my PhD I’ve not had much time.

    Will – it looks like you have the same key for both APIs, which I don’t think should be the case. Have you tried re-generating both keys with Google for the domain and checking they are correct? If you look locally at the files, then the keys are not necessary which would explain why you didn’t have a problem and do now.

  4. Will Postlethwaite

    HI Tom, Thanks for the quick reply, I have tried re-generating both api keys using both the links on here, which generate the same, both identical keys each time, resulting in it working on my computer but on the same url viewing on a different computer displays an error. How does the viewing it localy work if were viewing live on the same url. Could it mean its a server permissions error not letting google access the key in the server. I have strict access to upload file to the server through my ip. Im relatively new to google api UI, have viewed other examples using this example but i see nothing different with my code.

    Any thoughts are much appreciated,

    What you doing at PhD in?

  5. Just My Website

    Nice API Tom…

    I have used it in some of my developments. Dead easy to intergrate into code etc…

  6. Alec

    This is a great article, thanks for the info. A lot og Google’s geographic ‘extras’ like ppc geo targeting are so inaccurate it is laughable.

  7. How to ensure the ‘correct’ variable is used in a loop with anonymous functions? | deepinphp.com

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

  8. Daniel

    Hi Tom,

    This is brilliant, I however, am having the same problem as .

    I also had a look at your example link and you too have the same API key for the both.

    Hope the PhD is going well!

  9. Tom

    Hi Will,

    For your domain, I seem to get a different Map API key when I generate it: “ABQIAAAAsUBf7URfT5H6A5BoAwmjTxT_x5LtjaQDlJW7p7KCNn5Z_ufybxTQ
    _vU5a0vnyvUw0sR77QEowvXR6A”. Maybe try with that? Hopefully it was just a hiccup.

    My PhD is in Artificial Intelligence! A bit different to all this! However, I’m just writing up my thesis and then will be moving to full time working in the world of internet/digital marketing. :)

    Daniel,

    Have you got a link to the page, and I can try to take a look?

    Thanks Alec and everyone else for the thanks messages. It is really cool to hear that people are using this. Silly situation that it is even necessary!

    -Tom

  10. home cctv quote

    Thanks for taking the trouble to show us how to do this, but is it ok to use on a commercial site ?

  11. Tom

    Hi! You’re welcome. Yes, it is absolutely fine to use it on any site. :)

  12. Hemsida

    Nice article. Thanks for sharing

  13. Mark

    Great tutorial Tom, thanks for the info.

  14. John

    Informative article. Thanks

  15. Alastair

    This is a great solution but do you have a set of code for v3? I am using Geonames but the response is often too slow to update and the standard in Google does not provide a full postcode.

  16. Joey Emery

    Hi Tom, thanks for this. You know I’m so so glad that it labels the North Sea on the initial map. Just incase people forget where it is. It’s a pretty useful feature google have added. Do you know when it was added?

    Thanks again.

  17. DC

    Hi guys we just wanted to let you know if anybody is looking for a simpler solution to this with Google streetview included as well as map view give us a shout. Were selling the complete script integrated into your site for £20.

  18. hemanth

    Thank you so much for providing such a wonderful article

  19. hemanth

    Hi Tom,
    I have been working on an asp.net webapplication. My requirement is to integrate google maps using uk postal code in my site. Currently I am running my appplication in local machine. It is not showing any map right now.
    actually localSearch.setSearchCompleteCallback() is not invoking , is it because i am running app in local machine or any other reason . One more thing i have generated keys for this using one of my other site and both keys are same right now.

    Please help me on this
    Thank you in advance

  20. Wilfred

    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

  21. Tom

    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?

  22. Wilfred

    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.

  23. Tom

    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?

  24. Wilfred

    yea, i was using it as postcode validator, so people fill in a valid postcode

  25. Echilon

    Excellent tutorial, it’s a shame you can’t get the country.

  26. Paul

    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.

  27. Alexander

    Thanks for this, looks to be just what I was searching for.

  28. Tomm174

    BTW
    AFAIK
    The ajax key is the same as the API key

  29. business cctv installers

    Do I need permission from google to use this ?

  30. Laphan

    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

  31. Chris

    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

  32. Jan

    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?

  33. Craig

    As Jan said above, is this possible.

    It would be nice to be able to do this as it would make life so much easier!

    Thanks

  34. Shaun Phillips

    Hi Guys
    I would love to use this for a form that when all fields are input it shows the desired location on map and also send the info to my email? any thoughts?

  35. Mark

    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

  36. Angus Carnie

    Very interesting – thanks

    Visit rap-excouriers

  37. Ravi

    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…

  38. Kevin Coyle

    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

  39. Kelly Jones

    Great post. Here’s a geocoding feature that will make your applications smarter and more interactive. Instead of displaying plain text, any address-centric data can be displayed on your site with a live map from Yahoo! or Google. Users will get more accurate information and be engaged in the process http://www.caspio.com/extend/platform-extensions/map-mashup.aspx

  40. Geoff Wilkins

    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)?

  41. Geoff Wilkins

    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)?

  42. Geoff Wilkins

    I worked out the answer to the above, and http://www.geoffwilkins.net/MyTemplate/googlemap-geocoding.htm is working fine – but I can’t work out how to incorporate Street View with this code – any answers?

  43. Jim

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

    Thanks

  44. parth khatri

    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

  45. Derek Bates

    Both my map and yours have stopped working. they return postcode not found. I think this is caused by the version 3 bit.

  46. Jon

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

  47. Sara

    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

Leave A Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>