Răsfoiți Sursa

Geocode address if no map location is set in location form

Alan Lam 4 ani în urmă
părinte
comite
d9f7e5de17

+ 4 - 0
controllers/location_form.php

@@ -72,6 +72,10 @@ if($submit) {
 			throw new RuntimeException(__("Name is required."));
 			throw new RuntimeException(__("Name is required."));
 		}
 		}
 
 
+		if(isset($address->postal_code, $address->country) && !$address->hasGeolocation()) {
+			$address->geocode();
+		}
+
 		$address->commit();
 		$address->commit();
 
 
 		$location->address_id = $address->id;
 		$location->address_id = $address->id;

+ 1 - 12
controllers/tickets_ajax.php

@@ -67,18 +67,7 @@ $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->geocode();
 			$address->commit();
 			$address->commit();
 
 
 			$location = new Location();
 			$location = new Location();

+ 17 - 0
engine/Address.php

@@ -2,6 +2,8 @@
 
 
 namespace App;
 namespace App;
 
 
+use Exception;
+
 /**
 /**
  * Class Address
  * Class Address
  * @property int $id
  * @property int $id
@@ -40,4 +42,19 @@ class Address extends Model {
 		return isset($this->latitude, $this->longitude);
 		return isset($this->latitude, $this->longitude);
 	}
 	}
 
 
+	public function geocode(): ?array {
+		try {
+			$results = Geolocation::geocode($this->postal_code);
+			$result = $results[0];
+
+			$this->latitude = $result->geometry->location->lat;
+			$this->longitude = $result->geometry->location->lng;
+
+			return [$this->latitude, $this->longitude];
+		}
+		catch(Exception $e) {
+			return null;
+		}
+	}
+
 }
 }

+ 3 - 3
views/components/address_fields.php

@@ -7,8 +7,8 @@ namespace App;
  */
  */
 
 
 if(!$address->hasGeolocation()) {
 if(!$address->hasGeolocation()) {
-	$latitude = 51.5342116;
-	$longitude = -0.2917105;
+	$latitude = 0;
+	$longitude = 0;
 }
 }
 else {
 else {
 	$latitude = $address->latitude;
 	$latitude = $address->latitude;
@@ -42,7 +42,7 @@ else {
 	<div class="col-6">
 	<div class="col-6">
 		<div class="mb-3">
 		<div class="mb-3">
 			<label for="postal-code"><?=htmlspecialchars(__("Postcode"))?></label>
 			<label for="postal-code"><?=htmlspecialchars(__("Postcode"))?></label>
-			<input class="form-control" type="text" id="postal-code" name="postal_code" placeholder="<?=htmlspecialchars(__("Type postcode"))?>" value="<?=htmlspecialchars($address->postal_code)?>" />
+			<input class="form-control" type="text" id="postal-code" name="postal_code" placeholder="<?=htmlspecialchars(__("Type postcode"))?>" value="<?=htmlspecialchars($address->postal_code)?>" required />
 		</div>
 		</div>
 	</div>
 	</div>
 </div>
 </div>