Просмотр исходного кода

Geocode location when adding new location via a ticket

Alan Lam 4 лет назад
Родитель
Сommit
b75f1d80a4
3 измененных файлов с 50 добавлено и 0 удалено
  1. 1 0
      .env.example
  2. 12 0
      controllers/tickets_ajax.php
  3. 37 0
      engine/Geolocation.php

+ 1 - 0
.env.example

@@ -14,6 +14,7 @@ ENV=development
 
 
 GOOGLE_ANALYTICS_ID=
 GOOGLE_ANALYTICS_ID=
 GOOGLE_API_KEY=
 GOOGLE_API_KEY=
+GOOGLE_SERVER_API_KEY=
 
 
 RECAPTCHA_PUBLIC_KEY=
 RECAPTCHA_PUBLIC_KEY=
 RECAPTCHA_SECRET_KEY=
 RECAPTCHA_SECRET_KEY=

+ 12 - 0
controllers/tickets_ajax.php

@@ -67,6 +67,18 @@ $controller = new class($action) {
 
 
 			$address = new Address();
 			$address = new Address();
 			$address->postal_code = $postal_code;
 			$address->postal_code = $postal_code;
+
+			try {
+				$results = Geolocation::geocode($postal_code);
+				$result = $results[0];
+
+				$address->latitude = $result->geometry->location->lat;
+				$address->longitude = $result->geometry->location->lng;
+			}
+			catch(RuntimeException $e) {
+
+			}
+
 			$address->commit();
 			$address->commit();
 
 
 			$location = new Location();
 			$location = new Location();

+ 37 - 0
engine/Geolocation.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace App;
+
+use RuntimeException;
+
+class Geolocation {
+
+
+	/**
+	 * @param string $address
+	 * @param string $region
+	 * @return array
+	 * @throws RuntimeException
+	 */
+	public static function geocode(string $address, string $region = "gb"): array {
+		$query = [
+			"address" =>  $address,
+			"key" => $_ENV["GOOGLE_SERVER_API_KEY"],
+			"region" => $region,
+		];
+
+		$url = "https://maps.googleapis.com/maps/api/geocode/json?" . http_build_query($query);
+
+		$string = @file_get_contents($url);
+
+		$object = json_decode($string);
+		if(!$object) {
+			throw new RuntimeException("Failed to validate address.");
+		}
+		if($object->status !== "OK") {
+			throw new RuntimeException("Failed to validate address.");
+		}
+
+		return $object->results;
+	}
+}