You are here

public function Yandex::geocode in Geolocation Field 8.2

Same name and namespace in other branches
  1. 8.3 modules/geolocation_yandex/src/Plugin/geolocation/Geocoder/Yandex.php \Drupal\geolocation_yandex\Plugin\geolocation\Geocoder\Yandex::geocode()

Geocode an address.

Parameters

string $address: Address to geocode.

Return value

array||null Location or NULL.

Overrides GeocoderBase::geocode

File

modules/geolocation_yandex/src/Plugin/geolocation/Geocoder/Yandex.php, line 49

Class

Yandex
Provides the Yandex.

Namespace

Drupal\geolocation_yandex\Plugin\geolocation\Geocoder

Code

public function geocode($address) {
  if (empty($address)) {
    return FALSE;
  }
  $config = \Drupal::config('yandex_maps.settings');
  $lang = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  $url = Url::fromUri('https://geocode-maps.yandex.ru/1.x/', [
    'query' => [
      'geocode' => $address,
      'format' => 'json',
      'apikey' => $config
        ->get('key'),
      'lang' => strtolower($lang) . '_' . strtoupper($lang),
    ],
  ]);
  try {
    $result = Json::decode(\Drupal::httpClient()
      ->get($url
      ->toString())
      ->getBody());
  } catch (RequestException $e) {
    watchdog_exception('geolocation', $e);
    return FALSE;
  }
  $location = [];
  if (empty($result['response']['GeoObjectCollection']['featureMember'][0])) {
    return FALSE;
  }
  else {
    $coordinates = explode(' ', $result['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']);
    $location['location'] = [
      'lat' => $coordinates[0],
      'lng' => $coordinates[1],
    ];
  }
  if (!empty($result['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['boundedBy']['Envelope'])) {
    $lowerCoordinates = explode(' ', $result['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['boundedBy']['Envelope']['lowerCorner']);
    $upperCoordinates = explode(' ', $result['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['boundedBy']['Envelope']['upperCorner']);
    $location['boundary'] = [
      'lat_north_east' => $upperCoordinates[0],
      'lng_north_east' => $upperCoordinates[1],
      'lat_south_west' => $lowerCoordinates[0],
      'lng_south_west' => $lowerCoordinates[1],
    ];
  }
  if (!empty($result['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['description'])) {
    $location['address'] = $result['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['description'];
  }
  return $location;
}