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”
Brilliant, so simple been looking to the answer for this one for a while.
Well, Well, Well Mr Anthony… You decided to actually do some work sitting in the bloody caribean!! .. hehehhe
Nice post bud… I’ll have a good read later today when I am more awake, hope your doing well over there
Nice tutorial, but now I would like to go further and i am stuck. how can i query the geocoder from a from and retrieve the lon and lat from the javascript and inseet them into a database can you provide me some tips .
thanks a lot.
Hi Eliphas,
Previously, in the terms and conditions there was a clause that you couldn’t store geocode data back into a database; however it doesn’t seem to be there anymore.
Because the lat/long are retrieved via Javascript, you will need to use an AJAX request to send this information back to your server. You would probably create a server side script (PHP, ASP or similar), and then POST this data back to your server via an AJAX connection.
Your server side script would then receive the data and write it to your database.
If I get time, I will write a quick tutorial on caching geocoding results this week. That should help you if you need further assistance.
Hi,
Thanks for your tutorial, how would you get the following page to work and open the map directly on the passed postcode?
http://www.pets4homes.co.uk/pets4homes/home.nsf/TestMap?openForm&PostCode=bb24jh
I tried adding the following line to the onload event but it doesnt work :
usePointFromPostcode(document.getElementById(‘postcode’).value, setCenterToPoint)
Thanks
Mark
Hi Mark,
getElementById()
will only retrieve elements in the DOM tree; usually meaning elements you can see rendered on the page.What you need to do it to get a query string parameter from the URL; it isn’t as scary as it sounds, and there is a good article (complete with function) on it here:
http://www.netlobo.com/url_query_string_javascript.html
Using the function from the article, you’d then need to do something like:
I’ve not tested this code – but it should be something like that.
Good luck!! 🙂
THANK YOU.
I’ve been looking for something like this for years. Not only does it do a full postcode lookup, it doesn’t require my rather slow page to reload each time.
Thanks a lot for that. I shall try it later, but it is something I am about to try so should get me up and running really quickly. As far as I can see from the two keys, they are identical. Definitely worth a digg.
Hi thanks for your post –
I am very much starting out with this – so please forgive what might prove to be the stupidest question going – your gmap.js does not contain the api keys so I was concerned as to the format that they go in as I tried using the same tags as in the html and it doesn’t work – if i take them out I can get a lat long returned but that’s about all ( I wasn’t expecting a lat long without the api keys)
Many thanks again
Hi Tom
Great tutorial – any news yet on the caching geocoding – this is exactly what i need.
Keep up the great work.
Thanks
Hi Tim,
I see from your link you seem to be up and running now. I include the API key in the HTML file, not the Javascript file. In the HTML, I first include the 2 Google scripts (with API keys), and then include my gmap.js file, which has my functions.
Dave,
Busy week! I’ll try to get it up in the next couple of days.
Hi,
Firstly thanks for this example, it has proved to be extremely helpful.
I wondered if you could perhaps offer your insight too a small problem I am having. I have an array of postcodes which I want to place on a map, which I can do without problem. However each postcode has an associated info popup and I need to somehow feed the data I need to place in the popup to the result callback handler for the specific postcode it belongs to. I assume there’s a simple way of going about this but being a Javascript rookie I can’t seem to dig up any answers.
Tom, thanks very much for posting this, very useful information! Got it all working on my site with no problems.
[…] Using the default Google Maps API you can only include maps based on longitude and latitude and not on a UK postcode. After a bit of searching I found a brilliant blog post on Tom Anthony’s site that shows you how to use a few JavaScript functions to center the map on a postcode and then place a marker there as well. After following the tutorial I got the map in place but I wanted to extend it so that as the page loads it automatically centers on the postcode and places the marker there. […]
Hi Alan,
My preferred method for gathering up further information about map markers (for displaying in the info window or whatnot) is to store the informatino in an XML file, then fetch it with an AJAX connection.
You can then parse the XML with the built in DOM functions of Javascript, and grab your information.
I’m going to try to finishing up my caching tutorial today, and then if I have time this coming week I’ll make a tutorial showing what I mean above.
Chris,
Glad to hear it, thanks for the feedback! 🙂
[…] After my post Geocoding UK Postcodes with Google Maps API I’ve had a few people contact me about caching geocoding results back to a server, for subsequent pages. […]
The caching tutorial is up now; I hope that it answers your questions. 🙂
Hi Tom,
I need to pass the raw UK address (not formatted), Could you please help me out on this??
Harish
[…] Luckily there’s more than one way around the problem, and you can geocode postcodes for free (in one case using more than one Google API). Just look at the list of approaches and tutorials on Google’s own resource page for external geocoding tools. I rather like this method, as it’s relatively simple to code up… […]
Hi Tom,
Thanks very much for a great tutorial. Got it up and running in only a few minutes, and it’s saved us a great deal of time, effort and money pursuing alternates. I’ll be extending your code to provide “find your nearest” functionality shortly, and may post the amended code if there’s demand.
Thanks again for a great tutorial. Keep up the good work.
Tony.