Yandex.php in Geolocation Field 8.2
File
modules/geolocation_yandex/src/Plugin/geolocation/Geocoder/Yandex.php
View source
<?php
namespace Drupal\geolocation_yandex\Plugin\geolocation\Geocoder;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\Url;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Component\Serialization\Json;
use Drupal\geolocation\GeocoderBase;
use Drupal\geolocation\GeocoderInterface;
class Yandex extends GeocoderBase implements GeocoderInterface {
public function formAttachGeocoder(array &$render_array, $element_name) {
parent::formAttachGeocoder($render_array, $element_name);
$render_array['#attached'] = BubbleableMetadata::mergeAttachments(empty($render_array['#attached']) ? [] : $render_array['#attached'], [
'drupalSettings' => [
'geolocation' => [
'geocoder' => [
$this
->getPluginId() => [],
],
],
],
]);
}
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;
}
}