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”
Fantastic – thanks, this is way more accurate than the Maps API.
Is there any way I can calculate the UK postsode to postcode distance using google maps?
Hey, great article, but have you noticed the search doesn’t work anymore, I’m guessing google have changed something as my site and yours doesn’t work. :-S
This stopped working for me recently too!!! Oh no!!!!
Thank you for your script.
I got cache.php and geocode.php working fine. Just not clear how/where I add the 2 functions together in step 4 & 5. Appriciate some guidance. Thanks in advance.
This script is just what i was looking for.
I’m trying to make a link through to a google map from a dynamic page based on the postcode info for each entry in a mysql database. I’ve tried using the php method you suggested earlier but i’m stuggling to get it to work.
I’ve got the postcode from the url using GET but I don’t know where in the script to put the actual postcode so that the map loads centered on the postcode from the url rather than the GLatLng in the mapLoad function.
Is there a zip file containning sample script I can download to have a look at? thanks
Anyone have any suggestions how I could use this to get all of the applicable addresses in a zip? I.e. I want to not have to pay royal mail a fortune for simply getting the town/city from a post code (possible address list would be even better).
Thanks!
The accuracy of this data returned is now rated a “5” – The same as that of the Google Maps API 🙁
…but on closer inspection, it definitely still gives more accurate results!?
As part of a research project, I gathered an exhaustive list of all full UK postcodes (just under 2 million records) with their latitude and longitude.
If you’re interested in purchasing it then contact me via payman_labbaf [at] yahoo.com.
nice example
Great will use it easily now
Google have awful accuracy and DO NOT provide Geocoding. The maps do lack detail adn their premier programme (enterprise is a staggering £7700 and is not great compared to ViaMichelin solutions ) I know this from experience !
This has taken me so long to access and my developers have been flat out for months if finding a provider in the UK who offer Geocoding, reverse geocoding distance calculation, map management, route calculation with excellent maps and mapping technology)and accuracy. Coverage was key in choosing ViaMichelin too as they are a respected brand.
Google lacked support and the Geocoding was very expensive and not great. The other local providers could not stand up and deliver what is needed for me working in the transport industry as good logistics can save you money.
ViaMichelin were so cost effective I saved thousands of what I would ahev paid elsewhere and have a flawless solutions which has allowed me to win many more clients. I would highly recommend VIAMICHELIN API (store locators, Journey planners, directions, toll charges, congestion charge London and Live traffgic info) and the contact there is MARK who came to meet me to discuss my needs, there was no pressure and when I had all the info from 4 companies, It was a no brainer in choosing ViaMichelin Business Mapping and Geolocation for my GIS Geocoding web based webservices platform, It did not take long to developer inhouse and they host it too
Hi,
Thanks for this article but one more thing. Can we get the textual address by giving postal code? Is it possible? Just like point.lng(); , how can i get the textual address and the detail like street name etc. If possible then please help me.
Hi Paul,
Thanks Dear. I got it.
So is it possible to have a post code search whereby the webiste visitor could find a shop within x number of miles from his house? Without having to go to the Post Office?
Nice guide bud!
I believe the royal mail website has this facility.
I have a problem where I can either set a marker, or I can center the map. When I do both, then only the second one works.
{
usePointFromPostcode(“NW11AA”, placeMarkerAtPoint);
usePointFromPostcode(“NW11AA”, setCenterToPoint);
}
No marker will be shown for the above..