Add Google geolocation

This commit is contained in:
philipp lang 2024-12-10 11:13:30 +01:00
parent 6584953cd8
commit bb40476fdc
5 changed files with 53 additions and 14 deletions

View File

@ -2,7 +2,6 @@
namespace Zoomyboy\Osm; namespace Zoomyboy\Osm;
use Illuminate\Support\Facades\Http;
class Address class Address
{ {
@ -13,23 +12,13 @@ class Address
) { ) {
} }
public function getCoordinate(): ?Point public function getCoordinate($serviceClass): ?Point
{ {
if (!$this->address || !$this->zip || !$this->location) { if (!$this->address || !$this->zip || !$this->location) {
return null; return null;
} }
$response = Http::get('https://nominatim.openstreetmap.org/search?' . http_build_query([ return app($serviceClass)->getAddress($this->queryString());
'q' => $this->queryString(),
'format' => 'json',
'addressdetails' => 1,
]));
if (!$response->ok()) {
return null;
}
return count($response->json()) ? Point::from(['lat' => (float) data_get($response, '0.lat'), 'lon' => (float) data_get($response, '0.lon')]) : null;
} }
public function queryString(): string public function queryString(): string

View File

@ -40,7 +40,7 @@ class FillCoordsJob implements ShouldQueue
return; return;
} }
$coordinate = $address->getCoordinate(); $coordinate = $address->getCoordinate($this->model::geolocationService());
if (!$coordinate) { if (!$coordinate) {
return; return;

View File

@ -11,4 +11,6 @@ interface Geolocatable
public function destroyCoordinate(): void; public function destroyCoordinate(): void;
public function needsGeolocationUpdate(): bool; public function needsGeolocationUpdate(): bool;
public static function geolocationService(): string;
} }

25
src/GoogleService.php Normal file
View File

@ -0,0 +1,25 @@
<?php
namespace Zoomyboy\Osm;
use Illuminate\Support\Facades\Http;
class GoogleService
{
public function getAddress(string $query): ?Point
{
$response = Http::get('https://maps.googleapis.com/maps/api/geocode/json?' . http_build_query([
'address' => $query,
'key' => config('services.osm.google_key'),
]));
if (!$response->ok()) {
return null;
}
return Point::from([
'lat' => (float) data_get($response, 'results.0.geometry.location.lat'),
'lon' => (float) data_get($response, 'results.0.geometry.location.lng')
]);
}
}

23
src/OsmService.php Normal file
View File

@ -0,0 +1,23 @@
<?php
namespace Zoomyboy\Osm;
use Illuminate\Support\Facades\Http;
class OsmService
{
public function getAddress(string $query): ?Point
{
$response = Http::get('https://nominatim.openstreetmap.org/search?' . http_build_query([
'q' => $query,
'format' => 'json',
'addressdetails' => 1,
]));
if (!$response->ok()) {
return null;
}
return count($response->json()) ? Point::from(['lat' => (float) data_get($response, '0.lat'), 'lon' => (float) data_get($response, '0.lon')]) : null;
}
}