You are here

public function LocationAutocompleteController::autocomplete in Wunderground weather 8

Autocomplete for searching locations.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request made from the autocomplete widget.

Return value

\Symfony\Component\HttpFoundation\JsonResponse A json respoonse to use in the autocomplete widget.

1 string reference to 'LocationAutocompleteController::autocomplete'
wunderground_weather.routing.yml in ./wunderground_weather.routing.yml
wunderground_weather.routing.yml

File

src/Controller/LocationAutocompleteController.php, line 30
Contains \Drupal\wunderground_weather\Controller\LocationAutocompleteController.

Class

LocationAutocompleteController
Returns autocomplete responses for wunderground weather.

Namespace

Drupal\wunderground_weather\Controller

Code

public function autocomplete(Request $request) {
  $text = $request->query
    ->get('q');
  $client = new Client([
    'base_uri' => 'http://autocomplete.wunderground.com',
  ]);
  $response = $client
    ->get('aq?query=' . $text)
    ->getBody();
  $data = json_decode($response
    ->getContents());

  // Extract key and value from the returned array.
  $results = [];
  foreach ($data->RESULTS as $result) {
    $results[] = [
      'value' => $result->name . ' [' . $result->l . ']',
      'label' => $result->name,
    ];
  }
  return new JsonResponse($results);
}