View source
<?php
namespace Drupal\geolocation\Plugin\views\field;
use Drupal\views\ResultRow;
use Drupal\views\Plugin\views\field\NumericField;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\geolocation\LocationManager;
use Drupal\geolocation\ProximityTrait;
class ProximityField extends NumericField implements ContainerFactoryPluginInterface {
use ProximityTrait;
protected $locationManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, LocationManager $location_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->locationManager = $location_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('plugin.manager.geolocation.location'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['center'] = [
'default' => [],
];
$options['display_unit'] = [
'default' => 'km',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['center'] = $this->locationManager
->getLocationOptionsForm($this->options['center'], $this);
$form['display_unit'] = [
'#title' => $this
->t('Distance unit'),
'#description' => $this
->t('Values internally are always treated as kilometers. This setting converts values accordingly.'),
'#type' => 'select',
'#weight' => 5,
'#default_value' => $this->options['display_unit'],
'#options' => [
'km' => $this
->t('Kilometer'),
'mi' => $this
->t('Miles'),
'nm' => $this
->t('Nautical Miles'),
'm' => $this
->t('Meter'),
'ly' => $this
->t('Light-years'),
],
];
}
protected function getCenter() {
return $this->locationManager
->getLocation($this->options['center'], $this);
}
public function query() {
$query = $this->query;
$center = $this
->getCenter();
if (empty($center)) {
return;
}
$expression = self::getProximityQueryFragment($this
->ensureMyTable(), $this->realField, $center['lat'], $center['lng']);
$this->field_alias = $query
->addField(NULL, $expression, substr($this
->placeholder(), 1));
}
public function getValue(ResultRow $values, $field = NULL) {
$value = parent::getValue($values, $field);
$value = self::convertDistance((double) $value, $this->options['display_unit'], TRUE);
return $value;
}
public function render(ResultRow $row) {
$value = $this
->getValue($row);
if ($this->options['hide_empty'] && empty($value) && ($value !== 0 || $this->options['empty_zero'])) {
return '';
}
return parent::render($row);
}
}