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 stuck. Basically dont know much about javascript. I have add all code using my own keys. But page coming is giving error and shows blank. Javascript debugger says localsearch is null.
Also what I have to add in html file. Is there someone can share its html file. I only need to work for one postcode then i will configure for autogenrated postcode values. thanks
Hi,
how to get direction if I have got longitude and latitude for two places?
We are losing our workplace car park in the next few weeks. I am looking for a way to gather postcodes of colleagues at work and pour them into the Google map software in order to display, by way of pins, all employees who want to take part in a car sharing scheme. The idea being that anyone in work can see at a glance, the location of other employees who live nearby… a real good use for this kind of software don’t you think… any ideas anyone.
Although google now have a UK geocoding service available, since it’s launch they seem to have massively downgraded the accuracy of the service making it useless for most purposes. See here:
http://googlemapsapi.blogspot.com/2007/07/uk-geocoding-now-available-in-maps-api.html
Try comparing the two systems – the test page on the link above, and the test on *this* page. The method described on this page still seems to return accurate locations, but the Maps API Geocoder seems to return data which is up to a kilometer out.
I wonder why they’ve only degraded the accuracy of ONE of the APIs? Does anybody understand why they’ve done this?
Good tutorial to learn. I am looking for something similar to implement for one of my site. Will see how it goes.
Excellent job Tom – very helpful.
So here is one more thank you to add to your already long list!
Keep up the good work.
Vic
Hi Tom
Great little function, just one thing I am trying to pass info from a db to pop into the popup box for the marker. Just not sure how to pass the info.
Here is the code I am using:
var loc = ”;
var car = ”;
usePointFromPostcode(loc, placeMarkerAtPoint)
The var car is what I want to be displayed in the popup box next to the marker.
Thanks for help in advance. James
Hi – I am getting the “map has no properties” error, its driving me mental – anyone have any ideas??
My experience of using the Google Maps HTTP Geocoder for UK postcodes is that it is only uses part of the postcode, for example, XX2 1AN, XX2 1BB and XX2 1XY (if such postcodes exist) would all return the same lat/long values.
You might find MultiMaps offering is more accurate.
i am using google map for showing path for two places using my own points. when i am using this “Geocoding UK Postcodes with Google Map API” i am not able to get the path. waht to do
I’m trying to get a map of the DL12 postcode area. Will doing what you suggest ge theis for me?
lookup reverse phone number…
Which cell reverse phone lookup providers are you relying on? There are dozens of cell reverse services but you want to make sure you’re using the most accurate information available, right?…
Hello,
Could you please provide me some guidance regarding how exactly link gets formed
wen you enter any street address in the address bar of web browser?
Does any API do this whole function of locating that place? Actually I am new to all these things, so I dont have much idea about this.
Thank you.
Hi Tom,
I have found the tutorial to get the marker up very useful especially because I’m not a pro at javascript.
This will give you an idea on what I’m up to.
‘http://mimtech.pepperio.net/contactus.html’
However, I’m not able to get the FROM functionality on my site working.
If you have a look at the URL above, you see a set of hard coded directions to my office. I’m trying to get this to look a bit more dynamic using a FROM – TO functionality of the maps. I have two options of design to do this:
1. To have the map by default as it is just now when the page loads and then giving an option at the bottom to get the use to type in From and To. The submit resulting a list of directions.
2. This option is to have the default map on loading of the page. Below the map there is a From input box. On submit it shows directions from the typed in Address / POSTCODE to my office (This is coded in the script).
I would like to put more emphasis on the use of “PostCode” in the “From” field.
Here is are some bits and pieces of the script:
if (GBrowserIsCompatible())
{
var map = new GMap2(document.getElementById(“map”));
var panel = document.getElementById(“panel”);
var dir = new GDirections(map, panel);
map.setCenter(new GLatLng(55.863741, -4.24171), 14);
var marker = new GMarker(new GLatLng(55.863741, -4.24171));
map.addOverlay(marker);
var html=” ” +
“MIM Technologies Ltd” +
“141 St James Road, G4 0LT” +
“Tel: (0044) 0141 3038239”;
marker.openInfoWindowHtml(html);
map.addControl(new GSmallMapControl());
}
I have tried various other functions but had no success. Can you please help me with this? Any help is appreciated.
Just to add that I’m using a CMS called Pepperio to do the website.
Thanks!
Chandra
We’ve been giving this a go, but found there was a real lack of a decent free postcode finder in the UK in the first place – which we needed for some data in the first place. So we didn’t have much to work with.
When our planned tool is complete we’ll post here again.
Nice one!!
Can we have some workaround to use this server side so that we can store the GECOCODES in storage file and then display the multiple address at same time on the map.
e.g i have multiple office location in UK, and i need to show them at same time on map.
Hi Tom,
Can you suggest any of these third party services that you referred to?
I have given my programmer your URL to take a look at your Google solution, but I would like a backup in case he sees a problem.
Thanks,
Robert
Used this code for generating a map recently to show local stockists of a product. Have a database of postcodes to find the nearest 10 stockists, and then use their postcodes with this code to plot pins on the map.
So using the AJAX function I just ran a loop for all 10 stockists. The pins are plotted fine. All brilliant!
Then tested in the dreaded IE! Some of the bubbles had swapped marker. No idea why at all. I bodged a function to delay the loop for half a second before running the next postcode search and what do you know it works now.
Any ideas?
Thanks for this. Very clear and understandable, helped me a lot. In fact it helped me get a job.
Thanks, this helped me a lot.