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.
Awesome script!
Thanks for the help.
If there is any way you can also extract address details?
Hi there
Firstly, Thanks for the great and helpful article, and I’m not sure if this is already in the comments, but i’d like to contribute something back:
You should change:
[code]
mapload();
GUnload();
[/code]
to
[code]
mapload();
$(window).unload( function () { GUnload(); } );
[/code]
because It will help plenty people trying to use this code:
[code]
GEvent.addListener(marker, “click”, function() {
marker.openInfoWindowHtml(“Marker Wants to work“);
});
[/code]
which won’t work after GUnload(); is called. The GUnload() function removes all event handlers from the map.
Description:
Dismantles all registered event handlers in order to prevent memory leaks. Should be called as a handler for the unload event.
Hi Tom
Do you know whether there is any way with Google to get a more precise position on a road than you get from the postcode, e.g. W1T 1NJ give you a certain road, but 10 Rathbone Street, London W1T 1NJ is more accurate still?
Would a database of all UK postcodes offer the same level of accuracy as your solution please Tom?
Many thanks for all your help!!!!
Hi,
First of all, great code. Thanks for sharing.
I need to put together a search/map on my site so that if I type in a postcode/geocode the nearest 10 landmarks in relation show up on the map.
I would be storing the landmark data in a sql database and calling these from the map but so far I have not been able to find a solution.
Is Geocoding the way to go for this?
Thanks for your help.
Ive have finaly found what i was looking for. this saves me time. i would like to thank you.
Google basis (free) does not provide address verification (Geocoding) as there is no UK postcode license.
This means postcode searches are very in-accurate. The proximity search is very poor, even for town searches, often not recognising locations.
This is why Google have a premier and a enterprise solution which still is more expensive and not as good as business mapping specialists like bIng and Via Michelin who also have API’s.
As a free lance developer, so serious business would use Google as the system is weak and really provides a watered down solution.
The Google free (basic service) still does not provide address verification as the Geocoding from Google is still poor and will always be as they want to paid their paid services.
Thus the accuracy is weak and often plotted way off from where the POI should be.
For maximum accuracy and customisation, no serious business of developer would use Google long term, not when mapping specialists like Bing and ViaMichelin offer low cost solutions which are 100 times better !
thanks, this has been so helpful. More accuracy!! Thanks again!
Hi Tom
Thanks for the great article.
Just to share that I want to use GeoCode only for getting the lat/long and feed it to the database table. Could you please guide me at how to use your code for this. Sorry to bother but its a matter of urgency. Would be grateful if you could please reply.
Many Thanks
Vivek
Has anyone migrated this to V3 of the Google Map API Javascript?
I am a web developer and had a 2 month project testing both solutions after reading the outcome of the IMFA regarding European business mapping providers.
The wikipedia page for Google states it only provide BASIC Geocoding, so Kieran I agree with you on the accuracy point. The data cannot be cached. The V3 version has too many bugs still Ben.
I noted that the free Google solution took twice as long to develop, had only basic Geocoding and everything else had to be developed from scratch I.e. criteria search, database management. Still Google business customers both paid (up to Β£7800) a year and free (if the solution will not be re sold (i.e. vehichle tracking) have no access to the UK postcode data from the royal mail as Google are no licensed (hence the often appalling accuracy) with only 4 digit postcode verification.
In a positive, Google is a pretty basic platform and for the most part is free to use and widely available and recognised.
The API platform from ViaMichelin (used a mixture of javascript skills) was offered to me on a free trial for 45 days and took only a few weeks to complete, Geocoding for address verification was included (so ideal for store finder, reserve and collect, etc and gave me access to live human support (to see what else I could do with their api). They provided me a platform with full Europe coverage and geocoded Ireland which Google could not offer for a price cheaper than the Google enterprise and premier.
Bing fell behind when it came to customer support as it was non existent and the former multimap owned company owned by microsoft took just over the 2 months to get back to me.
Like for like, The new ViaMichelin API solution wins, For a basic solution use Google, for business’s looking for real quality use Viamichelin
Here is a short tutorial implementing geocoding and reverse geocoding on the client side: tech.cibul.org/geocode-with-google-maps-api-v3
Here is a short tutorial implementing geocoding and reverse geocoding on the client side: http://tech.cibul.org/geocode-with-google-maps-api-v3
It is so great and easy. Thank you so much.
has any body worked on coding from uk to the rest of europe with google maps?
I stumpled upon this website: http://www.postcode-distance.com
It does make the job for me. Ok it’s not free, but they supply me with updates…
Maybe this is an alternative for professional projects that do not mind to semnd a few bucks…
Hope that helped somebody…
Anyway, thanks for the cool article…
Thanks its a great help – thaks for writting the article brother
We got 18 million postcode with L& A
Thanks
many thanks for a great simple script. Now just need to work out how to add the listener to enable click of the marker with popup info.
Thanks again!
Thats me got somthing for the weekend cheers
Its good to see that you have shared such a simple script. Hope it will help me to materialize my market plan.
Thanks for the great tutorial, its been a good read and given some top information on how to get the google maps API to work better for us π
I am trying to develop an online odering system, based around geographical areas for a new business of mine, have been trying to figure it out for weeks, have just found your site and has I guess driven me on the right track, still not sure, so will probably be back to ask some questions if that is ok…
Many thanks.
Thanks this tutorial is exactly what i needed thanks! I will be having a play later.
Hello, Tom. I am using your way of geocoding uk postcodes, which runs perfectly in IE8, but in IE7 and IE6, there are errors, and cannot show the map.
Have you noticed that?
Please run your own demo page under IE7 and IE6, and it will say two errors.
I wish you can see this. If your browsers are IE8, you can use IETester to see that under IE7/IE6. Many thanks.
I have been searching for some info on the Google Map API this is the best tutorial I have found so far – I have been getting no where until now.
Easily the best tutorial I’ve found for the Google Maps API – Thank you for the detailed information.
its very nice and really working good on my site
thank you very much tom. really nice tutorial…
very nice
Am looking for a free editable postcode map of the UK, I need each postcode area to be colour coded with my delivery charges. Is there anyone that can help me out
thankyou..perfect:)
Hi Tom great tutorial works great….. But only on one computer, works great on my macbook in which i developed it on) but not on my imac on the same internet connection.
if you have any thoughts is would be amazing – please help!
its displays the
“This web site needs a different Google Maps API key. A new key can be generated at http://code.google.com/apis/maps/signup.html.”
which i have seen others are getting but not working at all, I can get it to work on one but no other and I cant figure out why.
I am testing this on the link below
http://www.grenergysolar.com/map-stage1.html
Hi Tom great tutorial the best google api tutorial out there in fact, but….. i am having a slight problem, it works fine on the computer i built it on but on other computers it displays a messages saying i need to generate a new key, i think it might be some sort of permissions issue as it works fine on my computer. i have tested this on 3 other computers and the same massage id displayed
I am testing it on the link below
http://www.grenergysolar.com/map-stage1.html
any assistance would be much appreciated
Hi everyone! Thanks for all the feedback, and sorry to those who have asked questions that have gone unanswered. I’ve been so busy doing my PhD I’ve not had much time.
Will – it looks like you have the same key for both APIs, which I don’t think should be the case. Have you tried re-generating both keys with Google for the domain and checking they are correct? If you look locally at the files, then the keys are not necessary which would explain why you didn’t have a problem and do now.
HI Tom, Thanks for the quick reply, I have tried re-generating both api keys using both the links on here, which generate the same, both identical keys each time, resulting in it working on my computer but on the same url viewing on a different computer displays an error. How does the viewing it localy work if were viewing live on the same url. Could it mean its a server permissions error not letting google access the key in the server. I have strict access to upload file to the server through my ip. Im relatively new to google api UI, have viewed other examples using this example but i see nothing different with my code.
Any thoughts are much appreciated,
What you doing at PhD in?
Nice API Tom…
I have used it in some of my developments. Dead easy to intergrate into code etc…
This is a great article, thanks for the info. A lot og Google’s geographic ‘extras’ like ppc geo targeting are so inaccurate it is laughable.
Hi Tom,
This is brilliant, I however, am having the same problem as .
I also had a look at your example link and you too have the same API key for the both.
Hope the PhD is going well!
Hi Will,
For your domain, I seem to get a different Map API key when I generate it: “ABQIAAAAsUBf7URfT5H6A5BoAwmjTxT_x5LtjaQDlJW7p7KCNn5Z_ufybxTQ
_vU5a0vnyvUw0sR77QEowvXR6A”. Maybe try with that? Hopefully it was just a hiccup.
My PhD is in Artificial Intelligence! A bit different to all this! However, I’m just writing up my thesis and then will be moving to full time working in the world of internet/digital marketing. π
Daniel,
Have you got a link to the page, and I can try to take a look?
Thanks Alec and everyone else for the thanks messages. It is really cool to hear that people are using this. Silly situation that it is even necessary!
-Tom
Thanks for taking the trouble to show us how to do this, but is it ok to use on a commercial site ?
Hi! You’re welcome. Yes, it is absolutely fine to use it on any site. π
Nice article. Thanks for sharing
Great tutorial Tom, thanks for the info.
Informative article. Thanks
This is a great solution but do you have a set of code for v3? I am using Geonames but the response is often too slow to update and the standard in Google does not provide a full postcode.
Hi Tom, thanks for this. You know I’m so so glad that it labels the North Sea on the initial map. Just incase people forget where it is. It’s a pretty useful feature google have added. Do you know when it was added?
Thanks again.
Hi guys we just wanted to let you know if anybody is looking for a simpler solution to this with Google streetview included as well as map view give us a shout. Were selling the complete script integrated into your site for Β£20.
Thank you so much for providing such a wonderful article
Hi Tom,
I have been working on an asp.net webapplication. My requirement is to integrate google maps using uk postal code in my site. Currently I am running my appplication in local machine. It is not showing any map right now.
actually localSearch.setSearchCompleteCallback() is not invoking , is it because i am running app in local machine or any other reason . One more thing i have generated keys for this using one of my other site and both keys are same right now.
Please help me on this
Thank you in advance