Geolocation.php 752 B

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace App;
  3. use RuntimeException;
  4. class Geolocation {
  5. /**
  6. * @param string $address
  7. * @param string $region
  8. * @return array
  9. * @throws RuntimeException
  10. */
  11. public static function geocode(string $address, string $region = "gb"): array {
  12. $query = [
  13. "address" => $address,
  14. "key" => $_ENV["GOOGLE_SERVER_API_KEY"],
  15. "region" => $region,
  16. ];
  17. $url = "https://maps.googleapis.com/maps/api/geocode/json?" . http_build_query($query);
  18. $string = @file_get_contents($url);
  19. $object = json_decode($string);
  20. if(!$object) {
  21. throw new RuntimeException("Failed to validate address.");
  22. }
  23. if($object->status !== "OK") {
  24. throw new RuntimeException("Failed to validate address.");
  25. }
  26. return $object->results;
  27. }
  28. }