Monday, 13 August 2018

Converting UK PostCode To Longitude And Latitude With PHP

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 manged to find a site called www.streetmap.co.uk 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 = "http://www.streetmap.co.uk/streetmap.dll?GridConvert?name=".$code."&type=Postcode";
  4.  
  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);
  10.  
  11. preg_match('#long \(wgs84\)\s*?\\s*?\\S{2,3}:\S{2}:\S{2} \( (.*?) \)#i',$output,$longMatch);
  12. preg_match('#lat \(wgs84\)\s*?\\s*?\\S{2,3}:\S{2}:\S{2} \( (.*?) \)#i',$output,$latMatch);
  13. $long = $longMatch[1];
  14. $lat = $latMatch[1];
  15.  
  16. return array($lat,$long);
  17. }
  18.  
  19. To use the function use the following, in this case I am looking at the BBC studio in London.
  20.  
  21. $geog = postCode2Geog('W1A 1AA');
  22.  
  23. This produces the result of 51.518561 latitude and -0.143800 longitude, which seems to check out.
  24.  
  25. 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.

0 comments:

Post a Comment