Posted By

SamBenson on 09/24/09


Tagged

sql php google maps longitude latitude radius


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

huynguye


SQL query to find all retailers within a given radius of a Latitude and Longitude


 / Published in: PHP
 

Use this query to return all rows in the table retail_items that are within the given radius of $latitude and $longitude.

  1. function retailerSearch($latitude, $longitude, $radius){
  2. $latitude = (int)$latitude;
  3. $longitude = (int)$longitude;
  4. $radius = (int)$radius;
  5. $degree = '69.17032342863616';
  6.  
  7. $dpmLAT = (1 / $degree);
  8. $radiusLAT = ($dpmLAT * $radius);
  9. $minLAT = ($latitude - $radiusLAT);
  10. $maxLAT = ($latitude + $radiusLAT);
  11.  
  12. $mpdLNG = ($degree * cos($latitude * (pi / 180)));
  13. $dpmLNG = (1 / $mpdLNG);
  14. $radiusLNG = ($dpmLNG * $radius);
  15. $minLNG = ($longitude - $radiusLNG);
  16. $maxLNG = ($longitude + $radiusLNG);
  17.  
  18. $subQuery = "
  19. SELECT
  20. `retail_id`
  21. FROM
  22. `retail_locations`
  23. WHERE
  24. `latitude` BETWEEN {$minLAT} AND {$maxLAT}
  25. AND
  26. `longitude` BETWEEN {$minLNG} AND {$maxLNG}
  27. ";
  28.  
  29. $query = "
  30. SELECT
  31. *
  32. FROM
  33. `retail_items`
  34. WHERE
  35. `id` = (
  36. {$subQuery}
  37. )
  38. ";
  39.  
  40. echo $query;
  41.  
  42. }

Report this snippet  

You need to login to post a comment.