1
0

geolocation.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. class Geolocation {
  3. const UNIT_MILES = 0;
  4. const UNIT_KILOMETERS = 1;
  5. const MILES_IN_KM = 0.621371;
  6. const KMS_IN_MILE = 1.60934;
  7. public static function getBounds($lat_lng, $distance, $units = Geolocation::UNIT_MILES) {
  8. list($latitude, $longitude) = $lat_lng;
  9. // Find latitude radius
  10. for($latitude_radius = $found_distance = 0; $found_distance < $distance; $latitude_radius += 0.001) {
  11. $found_distance = Geolocation::getDistance($lat_lng, [$latitude + $latitude_radius, $longitude], $units);
  12. }
  13. // Find longitude radius
  14. for($longitude_radius = $found_distance = 0; $found_distance < $distance; $longitude_radius += 0.001) {
  15. $found_distance = Geolocation::getDistance($lat_lng, [$latitude, $longitude + $longitude_radius], $units);
  16. }
  17. $min_latitude = $latitude - $latitude_radius;
  18. $max_latitude = $latitude + $latitude_radius;
  19. $min_longitude = $longitude - $longitude_radius;
  20. $max_longitude = $longitude + $longitude_radius;
  21. return (object) [
  22. "southWest" => [$min_latitude, $min_longitude],
  23. "northEast" => [$max_latitude, $max_longitude],
  24. ];
  25. }
  26. public static function getDistance($from, $to, $units = Geolocation::UNIT_MILES) {
  27. if(empty($from) || empty($to)) {
  28. return false;
  29. }
  30. $src_lat = $from[0];
  31. $src_lng = $from[1];
  32. $lat = $to[0];
  33. $lng = $to[1];
  34. $delta_lng = deg2rad($lng-$src_lng);
  35. $delta_lat = deg2rad($lat-$src_lat);
  36. $radius = 6371;
  37. $a = pow(sin($delta_lat/2), 2) + cos(deg2rad($lat))*cos(deg2rad($src_lat))*pow(sin($delta_lng/2), 2);
  38. $c = 2*atan2(sqrt($a), sqrt(1-$a));
  39. $distance = $radius*$c; // distance in km
  40. switch($units) {
  41. case Geolocation::UNIT_MILES:
  42. return round($distance*10)/10;
  43. case Geolocation::UNIT_KILOMETERS:
  44. return round($distance / 0.1609344)/10;
  45. default:
  46. return false;
  47. }
  48. }
  49. /**
  50. * @param $address
  51. * @param string $region
  52. * @return array
  53. * @throws Exception
  54. */
  55. public static function geocode($address, $region = "uk") {
  56. $query = [
  57. "address" => $address,
  58. "key" => GOOGLE_API_KEY,
  59. "region" => $region,
  60. ];
  61. $url = "https://maps.googleapis.com/maps/api/geocode/json?" . http_build_query($query);
  62. $string = @file_get_contents($url);
  63. $object = json_decode($string);
  64. if(!$object) throw new Exception("Failed to validate address.");
  65. if($object->status != "OK") throw new Exception("Failed to validate address.");
  66. $results = $object->results;
  67. return $results;
  68. }
  69. }