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.
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
Hi,
I have a table of UK postcodes stored in a MySQL database that I want to plot on a Google map.
Does any one have any advice on how I could go about doing this? I have read through all the 100s of comments but can’t quite work it all out since everyone has slightly different requests.
Thank you.
NickC – Thanks for the tip! That does indeed stop the text from spilling out.
Great tutorial.
Just going through it now.
Just one questions, I already have a Google Maps API key and have just got a Google AJAX API key
However, looking at your code (demo page) the 2 keys you have are the same code?? Is it the GOogle Maps one or AJAX one?? Do I need the reference to both somewhere??
Thanks
Its OK, my mistake. Just generated another Google Maps API Key and its the same as the AJAX one
Followed your instructions but not quite working. when enter location or postcode and press center map and place marker nothing happens.
Ideally I want it to enter postcode, press button and it centres AND places marker on location
Thanks
PS – How do you get the “controls” to display – the zoom in and out etc
I have a slight problem
This is my code
Search
function CheckKey() {
if (event.keyCode == 13) {
usePointFromPostcode(document.getElementById(‘postcode’).value, showPointLatLng);
}
}
If i enter a post code then click the search button everything is fine. But of I press the enter key which i have captured it goes to the function, but never actually does a new search and i just get the same results returned from the last search. Does anyone know why this could be happening. if i put an alert just before it calls localSearch.execute(postcode + “, UK”); then the alert will come up. As i said works OK on click but not on key down. Has anyone had a problem like this?
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!”);
}
});
alert(‘hello’)
localSearch.execute(postcode + “, UK”);
}
Hi Tom
What I need is the uk complete uk postal codes and the longditude
& latitudes numbers to put into our site data base. I personal am not a web designer, so this is what I have been told that I need.
Is this posible to get ?
Vernon
Hi Tom,
This code has been a great tool for our site, however i am having issues with multiple calls the the usePointFromPostcode() function in IE although it works absolutly fine with Firefox. Could you please email me and i will give you access to our website and then we can talk about the issue here. We can also look at providing you some funding for any work you carry out for us.
Thanks
Scott
Thanks a lot for this, a legendary bit of work. Added a tag for django template language at: http://www.djangosnippets.org/snippets/1336/
This is an excellent soltion
i have done exactly as you have said … but for some reason i cant see the marker when i click on the buttons … i guess its not working properly … help is needed please. help as i need to integrate it in my classified adverts site.
Cheers … hope it works out ..
For anyway who is a novice like me and need the exact code to have your map load from a postcode stored in session variable – have a look at this link.
http://forum.websitebaker2.org/index.php?topic=12846.0
Absolutely fantastic post by the way, been looking to do this for a long time now
Might be useful to some to know that Google now has a RESTful interface to their AJAX Search API: http://code.google.com/apis/ajaxsearch/documentation/#fonje
Wow this is great, its really what I was looking for.
I have a slight problem though, on a basic HTML page the code workd fine but when I place it on an asp.net form I cant get it to work.
I read further up the thread and tried what one user suggested, to put runat=server in the controls, i tried it in the input tag and the others too but still cant get it working.
Any one cast any light?
Thanks
Tino
aspx
heres a little something created with similar geocoding. This is a google / ebay api mashup and pin points used cars for sale via Ebay auction listings. Have a go! http://www.find-cars-4-sale.co.uk/
Would it be possible to provide an example using RESTful interface returning JSON object for ASP.NET C#?
I belive it supports the GET method
Regards
Tino
This is great. It also shows great weaknesses in my understanding of javascript.
Try as I might, I can’t figure out how to make the system work off a postcode variable. As stated, onload doesnt work as a method to trigger the map to use a postcode. I cant find a place / modification which loads themap according to a postcode variable either.
I am obviously being thick. Does anyone know/already have a variant of this code which works from a postcode variable passed to the code (or even a hardwired postcode rather than coords)?
Many thanks if anyone can help with this, it is driving me mad…
Oops.
Thanks so much Martin, I failed to see your link (just about as well as I failed to find the information elsewhere!!)! For those looking for the exact code to display a map by postcode variable without a click, as Martin above pointed out, the solution is here:
http://forum.websitebaker2.org/index.php?topic=12846.0
Well thanks to Tom’s tutorial I’ve finally managed to get driving directions with accurate start and end points using the Google Maps API. It’s only taken me a year to work it out.
Here’s an example for anyone struggling with the same thing http://www.anywherecouriers.co.uk/maps/directions-with-uk-geocoding.html
It’s probably not the most elegant solution but it works and I’m happy.
Thanks very much for this article Tom.. I have also made some additions to it like adding reverse geocoding.. getting address details from latitude and longitude.
However, is there a possibility we can create a dll or a webservice that does that.. What i am trying to say since it uses Ajax/javascript that runs only on client side.. can we trick a page into thinking that it has been rendered on the browser to invoke the javascript..
I have been trying to find a way to do that but have not been successful.
Not sure if anyone else has tried it yet. if so do let me know..
Hi, thanks for Great tutorial.
I am have a problem all to piont i put on the map have the same text can some see what i am doing wrong
function usePointFromPostcode(postcode,ref) {
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);
var marker = new GMarker(point);
GEvent.addListener(marker, “click”, function() {
marker.openInfoWindowHtml(InfoText[ref]);
});
map.addOverlay(marker);
}
else {
/* SKIP THAT PROPERTY CUZ I CAN’T FIND IT! */
}
});
localSearch.execute(postcode + “, UK”);
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != ‘function’) {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function addUnLoadEvent(func) {
var oldonunload = window.onunload;
if (typeof window.onunload != ‘function’) {
window.onunload = func;
} else {
window.onunload = function() {
oldonunload();
func();
}
}
}
addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
Welcome back Andrew here are you jobs for today
var InfoText=new Array();
InfoText[0] = ‘Job No. 3 Name : Price Phone ew’;alert(“0”);
usePointFromPostcode(‘wa1 0py’, ‘0’);
InfoText[1] = ‘Job No. 4 Name : 1 Phone 1’;alert(“1”);
usePointFromPostcode(‘1’, ‘1’);
InfoText[2] = ‘Job No. 4 Name : Tim Phone 1’;alert(“2”);
usePointFromPostcode(‘WA4 0Py’, ‘2’);
InfoText[3] = ‘Job No. 4 Name : a Phone 1’;alert(“3”);
usePointFromPostcode(‘WA2 0PY’, ‘3’);
InfoText[4] = ‘Job No. 4 Name : Price Phone ew’;alert(“4”);
usePointFromPostcode(‘wa3 0py’, ‘4’);
InfoText[5] = ‘Job No. 4 Name : price Phone 11’;alert(“5”);
usePointFromPostcode(‘PO45 2ah’, ‘5’);
InfoText[6] = ‘Job No. 4 Name : aa Phone 1’;alert(“6”);
usePointFromPostcode(‘1’, ‘6’);
InfoText[7] = ‘Job No. 4 Name : 1 Phone 1’;alert(“7”);
usePointFromPostcode(‘WA2 0PY’, ‘7’);
InfoText[8] = ‘Job No. 4 Name : 2 Phone 1’;alert(“8”);
usePointFromPostcode(‘S70 4ST’, ‘8’);
Many thanks for this great tutorial! Exactly what I was looking for 🙂
I had the same problem as Stew (June 7, 2007 @ 9:27 pm) and Matt (June 11, 2007 @ 4:20 pm)
The page loaded with the buttons (map, satellite, hybrid, and the pan zoom buttons), but no actual map… just a blank white background.
I even followed Tom’s advice and copied the the files from the demo page:
http://www.tomanthony.co.uk/demo/geocode_uk_postcode/
Still no joy.
Then I noticed the htm file ends with
<div id=”map”
I replaced this with
And bingo – it works.
Sorry, code didn’t come out.
I replace id=”map”
with
id=”map” style=”width: 700px; height: 450px”
and this worked
Nice, simple and clean.
thanks for a great tutorial.
Cheers!
>>but no actual map… just a blank white background.
the reason it comes out blank is because the map is styled [sized] in the css file, and by just copying the source you won’t have this styling info.
the quickest way to remedy this to get the demo working locally is to just put the style inline in the head of your doc.
#map
{
height: 500px;
width: 500px;
}
hope that helps.
rob ganly
Got the code working no problem and thanks very much for providing.
I am looking to embed the map into a PDF created from Coldfusion. When I add in the working code it produces nothin on the PDF.
Anyone any ideas?
I used your code a long time ago and has been working for well over a year but today it ha sstopped working and can see that the one on this site has stopped working too with the same errors fro JavaScript. Im gussing there will be a few people with this issue.
Im currently looking for an answer and will post her eif I find something.
A change must have been made with the API or a Windows update becase all the maps Ive looked at today that used this tutorial have now stopped working.
Ive been trying to find an answer to no avail. The error is that the map doesnt display at all and you get some javascript errors referrign to localsearch and glocalsearch.
Anyone with a fix it would be greatly appreciated.