Quick post if anyone is interested.
I currently have an out of date script running on my golf website golfshake.com which allows people to search for golf courses within a particular distance of a postal code in the UK. This is done by taking the latitude and longitude of a postal code and running a spatial query to find the golf courses within my database. This worked great until the free web services I was using for lat and lon postal code lookups was turned off unfortunately in the UK the postal data, including latitude and longitude values, is held by the Royal Mail and only available for some riduculous charge.
I’ve been meaning to fix this for some time and had bookmarked this site which had a neat script for extracting the longitude and latitude from postal codes in the UK using the Google maps API. This is great but it’s a UK only solution and works only on postal codes.
Well I’m glad to say that Google annouced at the beginning of July that UK geocoding is now available which extends to postal codes, addresses and locations.
Great I can now use the google API via a HTTP call to retrieve XML data for any location in the world but how can I use it in a PHP script ?
This will return an KML file containing; search term, full address, country, area, locality, longitude and latitude etc
Obviously I could use XML functions in PHP to browse the XML DOM, great article on this exact topic, but unfortunately PHP is limited in XML functionality in versions below PHP 5. You can even use CURL if it’s installed.
Thankfully the Google maps API is quite extensive and does not just provide XML output. One simple change of the output method to csv, will output simple data in CSV comma delimited format like :
Therefore for simple latitude and longitude data retriveal the PHP code is very simple indeed and is just a case of retrieving the URL and exploding the data into an array for use within your PHP code.
$address = urlencode($postal);
$url = “http://maps.google.com/maps/geo?q=$address&output=csv&key=YOUR_API_KEY”;
$content = file_get_contents($url);
$data = explode(”,”,$content );
Then you can use array calls to retrieve the data ie $data will get the lat and $data the lon.