Distance between two UK postcodes


/ Published in: PHP
Save to your folder(s)

A PHP function for calculating the distance between two UK postcodes


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function getDistance($postcode1, $postcode2) {
  4.  
  5. $coordinates1 = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($postcode1) . '&sensor=true');
  6. $coordinates1 = json_decode($coordinates1);
  7.  
  8. $coordinates2 = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($postcode2) . '&sensor=true');
  9. $coordinates2 = json_decode($coordinates2);
  10.  
  11. $earth_radius = 6371;
  12.  
  13. $dLat = deg2rad($coordinates2->results[0]->geometry->location->lat - $coordinates1->results[0]->geometry->location->lat);
  14. $dLon = deg2rad($coordinates2->results[0]->geometry->location->lng - $coordinates1->results[0]->geometry->location->lng);
  15.  
  16. $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
  17. $c = 2 * asin(sqrt($a));
  18. $d = $earth_radius * $c;
  19.  
  20. $d = $d * 0.621;
  21.  
  22. return $d;
  23. }
  24.  
  25. echo getDistance('W1T 1AL', 'WD6 1JG');
  26.  
  27. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.