View source
<?php
namespace Drupal\geofield\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\geofield\DmsConverter;
class LatLonFormatter extends GeofieldDefaultFormatter {
public static function defaultSettings() {
return [
'output_format' => 'decimal',
];
}
protected function formatOptions() {
return [
'decimal' => $this
->t("Decimal Format (17.76972)"),
'dms' => $this
->t("DMS Format (17° 46' 11'' N)"),
'dm' => $this
->t("DM Format (17° 46.19214' N)"),
'wkt' => $this
->t("WKT"),
];
}
protected function getOutputFormat() {
return in_array($this
->getSetting('output_format'), array_keys($this
->formatOptions())) ? $this
->getSetting('output_format') : self::defaultSettings()['output_format'];
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
unset($elements['output_escape']);
$elements['output_format'] = [
'#title' => $this
->t('Output Format'),
'#type' => 'select',
'#default_value' => $this
->getOutputFormat(),
'#options' => $this
->formatOptions(),
'#required' => TRUE,
];
return $elements;
}
public function settingsSummary() {
$summary[] = $this
->t('Geospatial output format: @format', [
'@format' => $this
->formatOptions()[$this
->getOutputFormat()],
]);
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$output = [
'#markup' => '',
];
$geom = $this->geoPhpWrapper
->load($item->value);
if ($geom) {
if ($geom
->getGeomType() != 'Point') {
$geom = $geom
->centroid();
}
if ($this
->getOutputFormat() == 'decimal') {
$output = [
'#theme' => 'geofield_latlon',
'#lat' => $geom
->y(),
'#lon' => $geom
->x(),
];
}
elseif ($this
->getOutputFormat() == 'wkt') {
$output = [
'#markup' => "POINT ({$geom->x()} {$geom->y()})",
];
}
else {
$components = $this
->getDmsComponents($geom);
$output = [
'#theme' => 'geofield_dms',
'#components' => $components,
];
}
}
$elements[$delta] = $output;
}
return $elements;
}
protected function getDmsComponents(\Point $point) {
$dms_point = DmsConverter::decimalToDms($point
->x(), $point
->y());
$components = [];
foreach ([
'lat',
'lon',
] as $component) {
$item = $dms_point
->get($component);
if ($this
->getSetting('output_format') == 'dm') {
$item['minutes'] = number_format($item['minutes'] + $item['seconds'] / 60, 5);
$item['seconds'] = NULL;
}
$components[$component] = $item;
}
return $components;
}
}