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); } }