You are here

public function GeocoderJsonConsumer::getAddress in Geocoder autocomplete 8

Return json list of geolocation matching $text.

Parameters

string $text: The text query for search a place.

Return value

array An array of matching location.

File

src/GeocoderJsonConsumer.php, line 53

Class

GeocoderJsonConsumer
Defines the GeocoderJsonConsumer service, for return parse GeoJson.

Namespace

Drupal\geocoder_autocomplete

Code

public function getAddress($text) {
  $language_interface = $this->languageManager
    ->getCurrentLanguage();
  $language = isset($language_interface) ? $language_interface
    ->getId() : 'en';
  $config = \Drupal::config('geocoder_autocomplete.settings');
  $query = [
    'address' => $text,
    'language' => $language,
    'sensor' => 'false',
    'region' => $config
      ->get('region_code_bias'),
  ];
  $uri = 'http://maps.googleapis.com/maps/api/geocode/json';
  $response = $this->httpClient
    ->request('GET', $uri, [
    'query' => $query,
  ]);
  $matches = [];
  if (empty($response->error)) {
    $data = json_decode($response
      ->getBody());
    if ($data->status == 'OK') {
      foreach ($data->results as $result) {
        if (!empty($result->formatted_address)) {
          $formatted_address = $result->formatted_address;
          $matches[] = [
            'value' => Html::escape($formatted_address),
            'label' => Html::escape($formatted_address),
          ];
        }
      }
    }
  }
  return $matches;
}