mirror of
https://github.com/Bigherollc/wticreatorstudio.git
synced 2026-09-29 03:13:24 -04:00
99 lines
2.9 KiB
PHP
99 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace Modules\LaraBuilder\Http\Controllers;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use GuzzleHttp\Client;
|
|
use GuzzleHttp\Exception\GuzzleException;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
|
|
class GoogleMapsController extends Controller
|
|
{
|
|
private string $apiKey;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->apiKey = config('larabuilder.google_maps_api');
|
|
}
|
|
|
|
/**
|
|
* @throws GuzzleException
|
|
*/
|
|
public function autocomplete(Request $request): JsonResponse
|
|
{
|
|
$query = $request->input('query');
|
|
|
|
$client = new Client();
|
|
$response = $client->get('https://maps.googleapis.com/maps/api/place/autocomplete/json', [
|
|
'query' => [
|
|
'input' => $query,
|
|
'key' => $this->apiKey,
|
|
],
|
|
]);
|
|
|
|
$data = json_decode($response->getBody());
|
|
|
|
// Extract and return the suggestions
|
|
$suggestions = [];
|
|
foreach ($data->predictions as $prediction) {
|
|
$suggestions[] = [
|
|
'name' => $prediction->description,
|
|
'place_id' => $prediction->place_id,
|
|
];
|
|
}
|
|
|
|
return response()->json($suggestions);
|
|
}
|
|
|
|
public function getLatLngByPlaceId(string $placeId): JsonResponse
|
|
{
|
|
$client = new Client();
|
|
|
|
try {
|
|
$response = $client->get("https://maps.googleapis.com/maps/api/place/details/json?place_id=$placeId&key=$this->apiKey");
|
|
$data = json_decode($response->getBody(), true);
|
|
|
|
if (isset($data['result']['geometry']['location'])) {
|
|
$location = $data['result']['geometry']['location'];
|
|
$lat = $location['lat'];
|
|
$lng = $location['lng'];
|
|
|
|
$result = ['lat' => $lat, 'lng' => $lng];
|
|
$status = 200;
|
|
} else {
|
|
$result = ['error' => 'Location not found'];
|
|
$status = 404;
|
|
}
|
|
} catch (GuzzleException $e) {
|
|
$result = ['error' => 'Unable to fetch lat/lng'];
|
|
$status = 500;
|
|
}
|
|
|
|
return response()->json($result, $status);
|
|
}
|
|
|
|
public function getAddressByLatLng($lat, $lng): JsonResponse
|
|
{
|
|
$client = new Client();
|
|
|
|
try {
|
|
$response = $client->get("https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=$this->apiKey");
|
|
$data = json_decode($response->getBody(), true);
|
|
|
|
if ($data['status'] === 'OK' && isset($data['results'][0]['formatted_address'])) {
|
|
$result = ['address' => $data['results'][0]['formatted_address']];
|
|
$status = 200;
|
|
} else {
|
|
$result = ['error' => 'Address not found'];
|
|
$status = 500;
|
|
}
|
|
} catch (GuzzleException $e) {
|
|
$result = ['error' => 'Unable to fetch address'];
|
|
$status = 500;
|
|
}
|
|
|
|
return response()->json($result, $status);
|
|
}
|
|
}
|