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”
Thanks Tom – this has inspired me to add a new feature on a website. I would like users to submit a form to a php function that writes a postcode to a text file and then a point is display on a google map on another page. Can you possibly give me any ideas how this might be done.
The idea is that people pledge to help with global warming and their pledge is marked on the map!
Can this method return street level info as well as postcodes from WGS84 coordinates?
Excellent & elegant example, thanks. This appears massively more accurate than Google’s much-vaunted “native” geo-coder. I wonder whether they’ve made it innacurate to keep the Royal Mail happy or something. Regardless, this is excellent, cheers again..
Just need to code up a server-side version now 🙂
Hi,
First of all – thanks for this code – It *almost* does what I’m trying to achieve
Basically, I want to use this – but actually pre-populate it, with a selection of Postcodes.
I’ve tried adding this into the JS:
localSearch.execute(“rh12 3he, UK”);
localSearch.execute(“rh14 9jl, UK”);
…but that doesn’t work.
Anyone got any suggestions? Heres an example of what I’ve tried:
http://www.gossamerlinks.com/testing_geo.html
TIA!
Andy
Does this all mean that its possible to do this:
Have a customer visit a web site and enter thier post code, then have google work out the distance from an office and send it back to the web site to see if they are too far away (say over 50Miles for example(?
Because that would be very cool.
[…] Geocoding UK Postcodes with Google Map API […]
Grewat code works well.
My question is:
I am looping through a database mapping the post codes, but I want to have an Information Window for each post code, how do I do this?
Hi Anthony,
I am looking for a way to find the postcode for a lat/long. Any ideas if i can acheive this and how?
Many Thanks
I would like to thank you for coming up with an genius bit of coding and sharing it with the rest of us, so that we may continue and build and adapt for our own applications.
Hi, thanks for this post.
This is much better than the Google geocoding API.
The long and lat that are returned are far more acurate than just putting your postcode into the geocoding api.
I will be using this technique on an estate agency website which I’m currently building.
It will be going live at http://www.sellinghouses.co.uk next week some time (w/c June 16) in the mean time you can sneak a preview at http://www.thetaylors.eu/properties.asp
Many thankd for the excellent post.
Sorry, the preview pages are at http://www.theonestopphoneyshop.co.uk/properties.asp
Thanks
http://www.inet-designs.co.uk
Thanks Tom for a great tutorial in geo coding. I’ve successfully managed to incorporate it into my site, but now I have another (I hope simple) problem.
Follow the link to view a property and you will see that the map tiles are not loading up correctly and the map page simply refuses to centre on the point. It always appears just off to the top left.
Can anyone help?
http://www.ukhousing.com/
Thanks for the great tutorial, unfortunately it only encouraged me to continue down the blind alley of trying to achieve something similar to what Malcan was looking for back in April 2007.
Eventually I looked around for another solution and what I couldn’t achieve after weeks of messing about with Google Maps was achieved with a solid afternoon’s work using Microsoft Virtual Earth. It’s slower and it’s Microsoft but it works! I just wish I could have achieved the same thing with Google Maps. http://www.anywherecouriers.co.uk/tariff1.html
Hi,
Sony : got the same problem a few days ago. It happens because you have your map loaded in an hidden div so the API cannot find your element’s width and height, thus it uses an element 0x0 and that’s the reason why it’s centered on the top-left corner. You can solve the problem by forcing the width and height in your function when you create your GMap2 object :
new GMap2(container, {size:new GSize(width,height)});
Hope it helps 🙂
For the people who had trouble with a Javascript error GlocalSearch not defined, paste your key directly into Tom’s example.
()
If like me you use the whole line that google gives you, they will set you up with a slightly different way of loading classes and GlocalSearch will not be in scope.
See http://code.google.com/apis/ajaxsearch/documentation/#The_Basics for more.
Hi
Does anyone know how I can make this example query and load load automatically?
I have the postcode already extracted from a database and just want the map to appear when a link is clicked.
The link is someones name – when their name is clicked a php programme runs pulling their details and postcode from a db.
I never use javascript so dont know how to automate js functions
thanks
Steve
Just to clarify – the map is displaying with the default co-ordinates set up in gmap.js. I dont import gmap.js I have it as a js routine internally to allow me to populate my_postcode variable dynamically from php & database, but dont know how to get
usePointFromPostcode(myPostcode, setCenterToPoint);
to run automatically,
Thanks
Steve
Hi,
Can someone tell me how to I change the deafult map that I get in the sample code of google? I would like to have a map of the uk in my website.
Thanks and regards,
Gil
Is it possible to do the reverse of this? I want to feed an address (either city, street, or even long/lat coordinates) and have Google report back a FULL UK postcode. Does this technique work around Royal Mail’s deathgrip on the copyright?
Hi Tom
I need u r help. I want to add google map in SEO. After finding my website this map should appear along with my keywords and web address. Please help me in this probelm.