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”
Hi Tom. I’ve been trying to develop a map that A) lets the user first type in their postcode , then B) allows them to move/adjust the position of the marker. Before saving it all back to a database! I’m trying to use your code with this script — http://mytubestop.com/add_marker_test.php — but can’t seem to get it working, I don’t know what the heck I’m doing. So , I’ve put the script back to normal, without your code added and was jut wondering, if you could help me.
If you can also tell me how to stop the user from adding multiple markers, I’d be really chuffed and would gladly give you a mention when my site is full off the ground. I can give you a sneak preview if you email me.
Thanks
Lee
Oh yeah! I love it when I answer my own questions 🙂
The Solution to my own problem is here: http://mytubestop.com/add_marker_test.php
Firstly, I’ve made the function placeMarkerAtPoint() dragable. Then I had to add var point = marker.getPoint(); so that the new co-ordinates would be updated on dragend, which for effect I’ve added to the info window.
Try it out. Put in a postcode, click Center Map then Place Marker. Then drag the marker to see the lat/lng variables update !!
Google’s built in Geocoding may be “over a mile off on some postcodes” but yours is several thousand miles off for others. Newport NP1 for example.
Tom,
I am just getting started with Javascript and HTML so am on a steep learning curve. I have a map onto which I am loading a handful of post codes from a file. The file contains the post code and a description. I drop into a loop calling usePointFromPostcode for each post code and these come out on the map fine.
I am stuck on adding the description to the marker using GMarker.bindInfoWindowHtml. How do I get the description for each post code through to the callback function so that it can add the description. I have tried a few things but the best I have achieved is for the description of the last post code to appear on all the markers.
can it run in local host.
Hi!
Thanks for guidance. Can some one guide me that how can all this be used in pure PHP. Like only the following URL
‘http://maps.google.com/maps/geo?output=csv&key=$api_key&q=’ is used to get CSV output from Google server for latitudes and longitudes.
nice solution. i still cant find anything from royal mail and there price is too expensive that i cant afford.
is there anything i can find for finding street name. like if i enter postcode and find the street address.
nice solution Tom. Im not sure what i would have done otherwise, brilliant thanks
Good Work.
hi, i have installed a property management app and need to import a UK postcode csv data file for the map and location finder to work. where can i get this from?
please help with this. thanks for your time. tony
Hi tom,
Good article and your work is great. First of all thanks for that.
But,
I want to find the distance between two postal codes which are entered in a form with Two textbox.
Waiting for you reply.
Thanks
Great tutorial, many thanks for this… exactly what I needed.
Great article. Was wondering, if you overlay an image over an area of a map, is it possible to work out which towns, countries the overlayed image covers?
Is there any way to plot an outline around a post code or a county or a suburb or a city…within the UK?
Hi,
I was having immense problems with gettin this to work, I kept getting the Glocalsearch not defined error. This is because you need version 2 of the maps JS and version 1.0 of the API JS. I just viewed the source of this page and copied and pasted the two Javascript references and changed the API keys and it all works fine now.
The Data Mapping engine in Data Transformation Server allows any-to-any transformations between different data formats. It includes complex data functions such as string, math, and conditional operations as well as DB and XML file look-up.
I’ve hard-coded the postcode in to my JavaScript function so it goes straight to that location on page load. But I have been unable to get the marker to be displayed upon page load – does anyone know how to do this?
hi, great tutorial first of al!
i just wondered if anyone could help me out on the terms side of things.
say i have a company website which has a database of my clients inc their addresses and i used the google api / ajax to store the long/lat numbers of their addresses in my database that ive returned from querying the google api, does this mean im infringing googles terms & conditions?
on first thought i dont see how you would be, as its not many calls which are made, only when a new client is added, we query google for their lat/long, store it for possible further use with a radius search.
whats peoples view on this???
tx :o)
Thank you for posting this blog entry, Tom. I found it very useful, and have implemented a slightly adapted version of your map system on the My School Christmas Cards website.
I have found a slight problem, though. The copyright notice at the bottom of the map can sometimes be too long for the map div to contain, and the notice spills out to the left. For example, try centring your map on the postcode SM7 2BQ. The copyright notice appears as follows: “Imagery ©2009 DigitalGlobe, Infoterra Ltd & Bluesky, GeoEye, Bluesky, The GeoInformation Group, Map data ©2009 Tele Atlas – Terms of Use”. In my browser, this stretches across your page margin, right over to the left-hand edge of the screen.
The same happens on the website that I have implemented the system on, except that the notice actually interferes with text that I have on the left of the map.
Is there any way around this?
Oliver – the simple way to get around the copyright text spilling out of the map container is to add an extra CSS command to your map div.
Just add ‘overflow:hidden’.
It’s cheap and cheerful solution but seems to do the trick.
Nick