ultimatepos/Modules/Tms/Services/TmsGeocodingService.php

48 lines
1.2 KiB
PHP

<?php
namespace Modules\Tms\Services;
class TmsGeocodingService
{
public function geocode(?string $address): ?array
{
$address = trim((string) $address);
if ($address === '') {
return null;
}
$url = 'https://nominatim.openstreetmap.org/search?'.http_build_query([
'q' => $address,
'format' => 'json',
'limit' => 1,
]);
try {
$context = stream_context_create([
'http' => [
'header' => "User-Agent: UltimatePOS-TMS/1.1\r\n",
'timeout' => 10,
],
]);
$response = @file_get_contents($url, false, $context);
if (! $response) {
return null;
}
$data = json_decode($response, true);
if (empty($data[0]['lat']) || empty($data[0]['lon'])) {
return null;
}
return [
'lat' => (float) $data[0]['lat'],
'lng' => (float) $data[0]['lon'],
];
} catch (\Throwable $e) {
\Log::warning('TMS geocoding failed: '.$e->getMessage());
return null;
}
}
}