Coordinate - Distance Lookup


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



Copy this code and paste it in your HTML
  1. <?
  2. # this snippet can be used to see if $postcode is within $radius of $shop_long $shop_lat
  3. $radius = trim($_GET['radius']);
  4. $postcode = trim($_GET['postcode']);
  5. $shop_long = 'LONGITUDE GOES HERE';
  6. $shop_lat = 'LATITUDE GOES HERE';
  7. $key = "GOOGLE_MAPS_API_KEY_GOES_HERE";
  8. if(!strstr($postcode,' ')){
  9. $len = strlen($postcode);
  10. $stlen = ($len == 7) ? 4 : 3;
  11. $start = substr($postcode,0,$stlen);
  12. $end = substr($postcode,-3);
  13. $postcode = $start.' '.$end;
  14. }
  15. $postcode = $postcode." UK"; # hack for UK postcodes to work properly :(
  16. $address = "http://maps.google.com/maps/geo?q=".urlencode($postcode)."&output=xml&key=$key";
  17. $page = file_get_contents($address);
  18. $xml = new SimpleXMLElement($page);
  19. list($customer_longitude, $customer_latitude, $altitude) = explode(",",$xml->Response->Placemark->Point->coordinates);
  20. ?>
  21. <h1>User Coordinates:</h1>
  22. <ul>
  23. <li>Longitude:<?=$customer_longitude?></li>
  24. <li>Latitude :<?=$customer_latitude?></li>
  25. </ul>
  26. <?
  27. $shop_longitude = (float) $shop_long;
  28. $shop_latitude = (float) $shop_lat;
  29. ?>
  30. <h1>Shop Coordinates:</h1>
  31. <ul>
  32. <li>Longitude:<?=$shop_longitude?></li>
  33. <li>Latitude :<?=$shop_latitude?></li>
  34. </ul>
  35. <?
  36.  
  37. $radius = $radius; // in miles
  38.  
  39. $lng_min = $shop_longitude - $radius / abs(cos(deg2rad($shop_latitude)) * 69);
  40. $lng_max = $shop_longitude + $radius / abs(cos(deg2rad($shop_latitude)) * 69);
  41. $lat_min = $shop_latitude - ($radius / 69);
  42. $lat_max = $shop_latitude + ($radius / 69);
  43.  
  44. $yn =((($customer_longitude >= $lng_min) && ($customer_longitude <= $lng_max)) && (($customer_latitude >= $lat_min) && ($customer_latitude <= $lat_max))) ? 'yes!':'nope!';
  45.  
  46. ?><h1>Within <?=$radius?> miles ? <?=$yn?></h1>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.