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”
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’);
Many thanks for this great tutorial! Exactly what I was looking for 🙂
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.
Sorry, code didn’t come out.
I replace id=â€mapâ€
with
id=â€map†style=”width: 700px; height: 450px”
and this worked
Nice, simple and clean.
thanks for a great tutorial.
Cheers!
>>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
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?
[…] Geocoding UK Postcodes with Google Map API | Tom Anthony – […]
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.
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.
Hi,
I have a small B & B business and when my guests use sat nav to find me it takes them 400/500yds away from me, where there are only two houses. I am one of four and one of them is a pub. Can you help or advise me on how to get this changed. Just spent an hour on google and got nowhere. I’m not very technically minded, so please keep it simple !!!!!
Thank you
Julie
I am wondering, does this API actually validate postcodes.
IE:
Apartment/Lodger Website where users need to enter in a postcode, which provides a Google map reference; therefore a Postcode is used to validate the location and create a map location at the same time.
What happens if the postcode is invalid? Will it be able to catch it and display it on the screen (or return it in some other way), rather than accepting it?
Thanks.
Hi,
I’m working on a personal site that uses the Google Maps API. The postcode the user submits is used to make an AJAX call to a home grown API that returns among other things, a load of postcodes in XML. I then iterate over these postcodes and place markers for each of them, i.e. all the postcodes that are related to the user-entered postcode.
However, I presume the localsearch performs asynchronously, and as such, some of my postcodes aren’t being geocoded – I believe because the previous localsearch hasn’t returned).
My code is something like:
[code]
for (var i = 0; i < stores.length; i++) {
var postcode = stores[i].getElementsByTagName(‘postcode’)[0].childNodes[0].nodeValue;
usePointFromPostcode(postcode, placeMarkerAtPoint);
}
[/code]
There are 5 postcodes in my XML being output by Firebug, but only the first and last are successfully geocoded. Any thoughts?
Hi,
Thanks for the great tutorial and demo. I would have never thought to use the ajax search with google maps but it seems to work pretty well, not sure how accurate some of the results are which are returned by google tho.
Thanks
Do you wish you could increase your online leads? Getting a 1st page Google ranking is easier and more cost-effective than you might think. We have helped a lot of businesses thrive in this market and we can help you! Simply hit reply and I’ll share with you the cost and the benefits.See you at the top!
Hello, i tried to find my friends house by using her postcode on google and it didnt work…:(
Tom,
A FANTASTIC tutorial there. I’m very impressed and have had little to no problems in implementation. However (you KNEW that was coming)… There is still a MASSIVE problem with accuracy in the data I’m getting back from google. If I may give an example: GU5 0HF comes back as 51.193548,-0.557244 when it SHOULD be 51.193608,-0.556999.
Is there something just inherently WRONG with googles data?
Michael, according to Royal Mail (who should know) GU5 0HF is High Street, Bramley, which Google correctly positions at 51.193548,-0.557244. 51.193608,-0.556999 is in Windrush Close, Bramley, which Royal Mail identifies as GU5 0BB. Google reverse geocodes this to 23-37 Windrush Close, Bramley.
Great tut! Helps me out loads! Thanks a lot.
I’ve just completed an adaptation of this to accurately geocode a batch of uk postcodes: http://wheresrhys.co.uk/2009/08/geocoding-in-the-uk/