You are here

OpenlayersGeolocationFormatter.php in Openlayers 8.4

File

modules/openlayers_geolocation/src/Plugin/Field/FieldFormatter/OpenlayersGeolocationFormatter.php
View source
<?php

namespace Drupal\openlayers\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\openlayers\OpenlayersService;
use Drupal\openlayers\MapSettings;

/**
 * Plugin implementation for an Openlayers Geolocation field formatter.
 *
 * @FieldFormatter(
 *   id = "openlayers_geolocation_formatter",
 *   label = @Translation("Openlayers Map"),
 *   field_types = {
 *     "geolocation"
 *   }
 * )
 */
class OpenlayersGeolocationFormatter extends OpenlayersFormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $entity = $items
      ->getEntity();
    if ($entity
      ->hasTranslation($langcode)) {
      $entity = $entity
        ->getTranslation($langcode);
    }
    $entity_type = $entity
      ->getEntityTypeId();
    $bundle = $entity
      ->bundle();
    $entity_id = $entity
      ->id();

    /* @var \Drupal\Core\Field\FieldDefinitionInterface $field */
    $field = $items
      ->getFieldDefinition();
    $settings = $this
      ->getSettings();
    $map = new MapSettings($settings['map']);
    $cache_tags = $map->cacheTags;
    $map = $map->settings;
    $results = [];
    $features = [];
    foreach ($items as $delta => $item) {
      $features[] = [
        'type' => 'latlon',
        'value' => explode(',', $item->value),
        'style' => [
          'fill' => [
            'color' => 'red',
          ],
          'stroke' => [
            'color' => 'black',
            'width' => 3,
          ],
        ],
      ];
    }

    // Add a specific map id.
    $map['id'] = 'openlayers-fieldname-map';
    $js_settings = [
      'map' => $map,
      'features' => $features,
      'settings' => [
        'zoom' => $settings['zoom'],
      ],
    ];
    $results[] = $this->openlayersService
      ->openlayersRenderMap($js_settings, $settings['height'] . $settings['height_unit'], $cache_tags);
    return $results;
  }

}

Classes

Namesort descending Description
OpenlayersGeolocationFormatter Plugin implementation for an Openlayers Geolocation field formatter.