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.
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:
The key to this Geocoder is only a single function:
It takes 2 arguments; [code]]czo4OlwicG9zdGNvZGVcIjt7WyYqJl19[[/code] is the postcode you want to look for, and [code]]czoxNzpcIiBjYWxsYmFja0Z1bmN0aW9uXCI7e1smKiZdfQ==[[/code] 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 [code]]czo3OlwiR0xhdExuZ1wiO3tbJiomXX0=[[/code] (often just called a point); I’ve supplied 2 sample functions, [code]]czoxOTpcIiBwbGFjZU1hcmtlckF0UG9pbnRcIjt7WyYqJl19[[/code] and [code]]czoxNjpcInNldENlbnRlclRvUG9pbnRcIjt7WyYqJl19[[/code] which do pretty much what they sound like they do.
We have a field for inputting a postcode, and I’ve added a button for placing a marker there. Where I have [code]]czoxODpcInBsYWNlTWFya2VyQXRQb2ludFwiO3tbJiomXX0=[[/code] you can put a reference to your own function, or you can even add a function right in there, like this:
If you are coming in from an RSS reader, either visit this blog post on the site, or see the demo page.
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.