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”
Dear Tom
we are currently building a website but have come to a halt re the geocoding, we need something that will provide a return of postcode, street name long/lat co-ords, also whether you can search on postcode info to return a list of available addresses which would then return the long/lat co-ords once selected, we have had some responses but the prices have been too high.
Any suggestions?
kind regards
Sharron Hibbert
Hi Tom,
Just want to say what an awesome tutorial! Exactly what I’ve been looking for, and I mean exactly!
Reading through the above posts, I arent sure if someone submitted this exact question and may have worded it slightly different, however:
Your geocoding form adds multiple markers on the map below, one marker for each postcode entered, which then stay on the map until you leave the page. How could I store the postcode entered into a list (txt, MySQL, etc) and then recall this list the next time the page is loaded so that the markers are still available? So effectively you are leaving a mark on a map for anyone else to see.
I have searched high and low to be able to do this and unfortunately to no avail (baring in mind I am a novice at server-side/scripting etc).
Will love ya forever!
Thanks
Alex
Ah, I think the caching tutorial answers my question!
However, do you know of a way to make this particular type of map work with sites such as MySpace seeing as MySpace dont allow Javascript (or even PHP)!
Essentially what I would like is a simple form for MySpace users to enter their postcode into a textbox, the postcode would be passed off to my database, then a marker would appear on the localised map along with all the other markers of submitted postcodes (by refresh or something). I know the other MySpace map providers use work arounds via logging IP address and displaying on a map, but this is not accurate enough for my needs of a local based profile that doesnt require worldwide tracking!
This may be slightly off topic to the original map tutorial but any advice in the right direction would be deeply appreciated!
Thanks
Alex
Hi Tom,
I have an requirement. 1) if need to pass the address in a text field, if i click on placemark or enter it should directly show the location in the Map. Could you please provide me the code or can u guide me on how to do this. one more option for me is 2) a link will there and some address will be associated to the link. If i click on the Link, this should show the location in the Map. Please let me know how to approach to this method.
Thanks in advance
Kiran jagarlapudi
Sharon –
I’m don’t think that Google Maps could do this. With Google Local Search you could get a list of addresses for businesses in the area of a postcode, but not all the addresses. So depending, that may be of some help to you. Otherwise have you tried http://www.postcodeanywhere.co.uk/ ?
Alex –
MySpace won’t allow any Javascript or iFrames, so the only solution you are left with is Flash. I think you could make a Flash form that used LoadVars to send the Postcode entered to your server, which would reply with a list of all Postcodes entered. Then use this very cool solution (which I only just found – am going to check it out more) to provide Google Maps via Flash:
http://www.afcomponents.com/components/g_map/
I think that would almost give you an entirely flash based solution, but I believe it would fall down as you couldn’t access Google Local search and thus couldn’t geocode the postcodes. You’d need to do that server side with one of the expensive databases. 🙁
Hi Tom,
Could you please give me an update on this asap.
I have an requirement. 1) if need to pass the address in a text field, if i click on placemark or enter it should directly show the location in the Map. Could you please provide me the code or can u guide me on how to do this. one more option for me is 2) a link will there and some address will be associated to the link. If i click on the Link, this should show the location in the Map. Please let me know how to approach to this method.
Thanks in Advance
Kiran
In your application if i want to print the latitude and longitude on the website rather than giving an alert message…how can i do that…please reply when u get time
regards
jitesh
Hi Tom,
Got my map working (no style css DOH)
Anyhow, I am desperately trying to ‘auto load’ a postcode (stored in a variable) on loading the page.
Any ideas????
Thanks
Hi again,
Managed to do the varible in a postcode.
If i place a marker then center the map, i lose the marker.
In reverse, if a center the map, then place a marker, the map zooms out to some default value. Can I set this default value??
Thanks
Hi,
Great Tutorial, Didn’t have any problems at all.
I have however tryed to use the returned point var to use in the CDirections of the Google Maps API, and for some reason all i get returned is Null for the search.results , Is there anything I am missing?
Think this would be a great addition to the functionality of ur gmap.js file.
Thanks
Hi Tom, thank you for the wonder script. I am now able to retreive many UK addresses and display them on my map.
I think that your solution is obsolete. The Google Maps API offers a way to geocode any UK ADDRESS or UK POSTCODE for free using the GClientGeocoder class in the API! You can pass it any international address, such as “Buckingham Palace, London” or just a postcode and it will return you detailed geocoded information.
FURTHER, Google offers a FREE UK/INTERNATIONAL HTTP geocoding service which returns, via plain old HTTP a nicely formatted XML structure of latitude/longitude and address information for any postcode/zip/address.
It is all here: http://www.google.com/apis/maps/documentation/index.html#Geocoding_Examples
And if you don’t believe the free http geocoding interface, try this address to geocode buckingham palace:
http://maps.google.com/maps/geo?q=SW1A1AA&output=xml&key=ENTER_YOUR_API_KEY
Has everyone else missed this??
Hi Matt,
I can assure you that this amount of people have not just missed Google’s geocoder!
However, until recently the geocoder was disabled for both the UK (and others, such as China), and would simply return error 603 (G_GEO_UNAVAILABLE_ADDRESS) and wouldn’t work (as is very well documented by a number of sutes).
FURTHER, I discuss accessing the Google Geocoder via HTTP in the post following this one. It too would return the same error.
I have checked it periodically, and it has always had the same error (confirmed less than a month ago, see for example here). However, it seems you have stumbled across it after they have updated it.
I’m not sure if this update is intentional and can’t find any news about it. If Google had brokered a deal, I’d expect there to be some news about it. I am going to watch this over the next few days, and if it continues to work, then I’ll be sure to update the tutorial.
hi tom,
this demo works fine in firefox2 but when i use ie7 i get no marker or anything. even on your demo page when i use the zoom feature using ie7 i just get back a blank map. ive even reset all manufacture setting in ie7 to no avail.
any ideas?
rickh
This is great and easy to use. However I am trying to automate this so when a page is loaded a postcode is grabbed from a querystring and then added to the function e.g usePointFromPostcode(‘postcode’, setCenterToPoint). It works great in IE but in firefox it is not working. The error I get is map has no properties. The map obviously isn’t loading in time. I have tried to set timers etc.. but can’t find a way around it. Does anyone have any ideas
Cheers. Have been pulling my hair out with this Postcode thing. Am just away to hack some of the code to make this do what I need it to.
Thanks again
Michael
Tom,
This looks like a wonderful resource, which I’m just trying to get my head around. However, is it superceded by Google’s July 6 announcement ‘UK Geocoding Now Available in the Maps API’, or is it complementary?
See http://googlemapsapi.blogspot.com/2007/07/uk-geocoding-now-available-in-maps-api.html
Thanks, Chris
[…] Please visit this tutorial by Tom Anthony which details how to do this. […]
Hi, fantastic example!
Just a quick question if you know the answer. I have a database written in MySQL and want to display a map based on the postcode in the db from a recordset. Rather than giving the user the ability to input via a form. Any ideas?
Thanks
Gareth
Thanks for this, I have implemented it on my pets for sale site pets4homes at http://www.pets4homes.co.uk