Converting UK PostCode To Longitude And Latitude With PHP

21st November 2008 - 2 minutes read time

This common problem has stumped many programmers in the past, so I thought I would add in my little part. Whilst doing research for this I managed to find a site called which has a nice little PostCode to geographical reference tool. Using a simple URL parameter I was able to give the site a PostCode and strip the longitude and latitude from the resulting HTML. Here is the function I came up with.

  1. function postCode2Geog($code){
  2. $code = strtolower(str_replace(' ','',$code));
  3. $uri = "".$code."&type=Postcode";
  5. $ch = curl_init($uri);
  6. curl_setopt($ch, CURLOPT_HEADER, 0);
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  8. $output = curl_exec($ch);
  9. curl_close($ch);
  11. preg_match('#long \(wgs84\)\s*?\<\/td\>\s*?\\S{2,3}:\S{2}:\S{2} \( (.*?) \)#i',$output,$longMatch);
  12. preg_match('#lat \(wgs84\)\s*?\<\/td\>\s*?\\S{2,3}:\S{2}:\S{2} \( (.*?) \)#i',$output,$latMatch);
  13. $long = $longMatch[1];
  14. $lat = $latMatch[1];
  16. return array($lat,$long);
  17. }

To use the function use the following, in this case I am looking at the BBC studio in London.

This produces the result of 51.518561 latitude and -0.143800 longitude, which seems to check out.

$geog = postCode2Geog('W1A 1AA');

Initial results from using this method seem promising, but the Streetmap site seems not to have been updated since 2004. I found this method after a few minutes searching, and I only needed to convert 20 or so postcodes into geographical coordinates. An alternative is to use a method that I have talked about previously in the post find longitude and latitude of PostCode or ZipCode using Google Maps And PHP, but that requires you to have a valid, working Google maps API key. This method is an alternative if you don't want to go down that route.


Fatal error: Call to undefined function curl_init() in C:\wamp\www\RICHARD-3\viewbusiness.php on line 12 CURL is enable in my server. Please help

saim (Thu, 05/09/2013 - 11:26)

CURL might be installed but what about the CURL-PHP extension? Check for your phpinfo() output. Actually, you seem to be running a Windows machine so you should go into your php.ini file and make sure that the php_curl.dll extension is enabled.

11 years on and thanks to very little progress being made by Streetmaps this little beauty is still working like a dream. I swapped out 

preg_match('#long \(wgs84\)\s*?\\s*?\\S{2,3}:\S{2}:\S{2} \( (.*?) \)#i',$output,$longMatch);

preg_match('#lat \(wgs84\)\s*?\\s*?\\S{2,3}:\S{2}:\S{2} \( (.*?) \)#i',$output,$latMatch);


 $long_pattern = '/x=[0-9]*/';
 $lat_pattern = '/&y=[0-9]*/';

 otherwise this is still a brilliant snippet, thanks for sharing :)

Michelle Morgan (Sat, 05/25/2019 - 03:09)

Add new comment

The content of this field is kept private and will not be shown publicly.