You are here

class GeolocationGeometry in Geolocation Field 8.3

Same name in this branch
  1. 8.3 modules/geolocation_geometry/src/Plugin/views/relationship/GeolocationGeometry.php \Drupal\geolocation_geometry\Plugin\views\relationship\GeolocationGeometry
  2. 8.3 modules/geolocation_geometry/src/Plugin/geolocation/DataProvider/GeolocationGeometry.php \Drupal\geolocation_geometry\Plugin\geolocation\DataProvider\GeolocationGeometry

Provides GPX.

Plugin annotation


@DataProvider(
  id = "geolocation_geometry",
  name = @Translation("Geolocation Geometry"),
  description = @Translation("Points, Polygons, Polyines."),
)

Hierarchy

Expanded class hierarchy of GeolocationGeometry

File

modules/geolocation_geometry/src/Plugin/geolocation/DataProvider/GeolocationGeometry.php, line 22

Namespace

Drupal\geolocation_geometry\Plugin\geolocation\DataProvider
View source
class GeolocationGeometry extends DataProviderBase implements DataProviderInterface {

  /**
   * {@inheritdoc}
   */
  protected function defaultSettings() {
    $settings = parent::defaultSettings();
    $settings['stroke_color'] = '#FF0044';
    $settings['stroke_color_randomize'] = TRUE;
    $settings['stroke_width'] = 1;
    $settings['stroke_opacity'] = 0.8;
    $settings['fill_color'] = '#0033FF';
    $settings['fill_color_randomize'] = TRUE;
    $settings['fill_opacity'] = 0.1;
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function isViewsGeoOption(FieldPluginBase $views_field) {
    if ($views_field instanceof EntityField && $views_field
      ->getPluginId() == 'field') {
      $field_storage_definitions = $this->entityFieldManager
        ->getFieldStorageDefinitions($views_field
        ->getEntityType());
      if (!empty($field_storage_definitions[$views_field->field])) {
        $field_storage_definition = $field_storage_definitions[$views_field->field];
        if (in_array($field_storage_definition
          ->getType(), [
          'geolocation_geometry_geometry',
          'geolocation_geometry_geometrycollection',
          'geolocation_geometry_point',
          'geolocation_geometry_linestring',
          'geolocation_geometry_polygon',
          'geolocation_geometry_multipoint',
          'geolocation_geometry_multilinestring',
          'geolocation_geometry_multipolygon',
        ])) {
          return TRUE;
        }
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getSettingsForm(array $settings, array $parents = []) {
    $element = parent::getSettingsForm($settings, $parents);
    $settings = $this
      ->getSettings($settings);
    $element['stroke_color'] = [
      '#type' => 'color',
      '#title' => $this
        ->t('Stroke color'),
      '#default_value' => $settings['stroke_color'],
    ];
    $element['stroke_color_randomize'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Randomize stroke colors'),
      '#default_value' => $settings['stroke_color_randomize'],
    ];
    $element['stroke_width'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Stroke Width'),
      '#description' => $this
        ->t('Width of the stroke in pixels.'),
      '#default_value' => $settings['stroke_width'],
    ];
    $element['stroke_opacity'] = [
      '#type' => 'number',
      '#step' => 0.01,
      '#title' => $this
        ->t('Stroke Opacity'),
      '#description' => $this
        ->t('Opacity of the stroke from 1 = fully visible, 0 = complete see through.'),
      '#default_value' => $settings['stroke_opacity'],
    ];
    $element['fill_color'] = [
      '#type' => 'color',
      '#title' => $this
        ->t('Fill color'),
      '#default_value' => $settings['fill_color'],
    ];
    $element['fill_color_randomize'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Randomize fill colors'),
      '#default_value' => $settings['fill_color_randomize'],
    ];
    $element['fill_opacity'] = [
      '#type' => 'number',
      '#step' => 0.01,
      '#title' => $this
        ->t('Fill Opacity'),
      '#description' => $this
        ->t('Opacity of the polygons from 1 = fully visible, 0 = complete see through.'),
      '#default_value' => $settings['fill_opacity'],
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function getLocationsFromViewsRow(ResultRow $row, FieldPluginBase $viewsField = NULL) {
    $locations = parent::getLocationsFromViewsRow($row, $viewsField);
    $current_style = $viewsField->displayHandler
      ->getPlugin('style');
    if (empty($current_style) || !is_subclass_of($current_style, 'Drupal\\geolocation\\Plugin\\views\\style\\GeolocationStyleBase')) {
      return $locations;
    }
    foreach ($locations as &$location) {
      if (!is_array($location)) {
        continue;
      }
      $location['#title'] = $current_style
        ->getTitleField($row);
      $location['#label'] = $current_style
        ->getLabelField($row);
    }
    return $locations;
  }

  /**
   * {@inheritdoc}
   */
  public function getShapesFromViewsRow(ResultRow $row, FieldPluginBase $viewsField = NULL) {
    $shapes = parent::getShapesFromViewsRow($row, $viewsField);
    if (empty($shapes)) {
      return $shapes;
    }
    $current_style = $viewsField->displayHandler
      ->getPlugin('style');
    if (empty($current_style) || !is_subclass_of($current_style, 'Drupal\\geolocation\\Plugin\\views\\style\\GeolocationStyleBase')) {
      return $shapes;
    }
    foreach ($shapes as &$shape) {
      if (!is_array($shape)) {
        continue;
      }
      $shape['#title'] = $current_style
        ->getTitleField($row);
    }
    return $shapes;
  }

  /**
   * {@inheritdoc}
   */
  public function getShapesFromItem(FieldItemInterface $fieldItem) {
    $settings = $this
      ->getSettings();
    $shapes = $locations = [];
    $this
      ->parseGeoJson($fieldItem
      ->get('geojson')
      ->getString(), $locations, $shapes);
    $positions = [];
    foreach ($shapes as $shape) {
      $random_color = sprintf('#%06X', mt_rand(0, 0xffffff));
      switch ($shape->type) {
        case 'Polygon':
          $coordinates = '';
          foreach ($shape->coordinates[0] as $coordinate) {
            $coordinates .= $coordinate[1] . ',' . $coordinate[0] . ' ';
          }
          $position = [
            '#type' => 'geolocation_map_polygon',
            '#coordinates' => $coordinates,
            '#stroke_color' => $settings['stroke_color_randomize'] ? $random_color : $settings['stroke_color'],
            '#stroke_width' => (int) $settings['stroke_width'],
            '#stroke_opacity' => (double) $settings['stroke_opacity'],
            '#fill_color' => $settings['fill_color_randomize'] ? $random_color : $settings['fill_color'],
            '#fill_opacity' => (double) $settings['fill_opacity'],
          ];
          $positions[] = $position;
          break;
        case 'MultiPolygon':
          $container = [
            '#type' => 'container',
            '#attributes' => [
              'class' => [
                'geolocation-multipolygon',
              ],
            ],
          ];
          foreach ($shape->coordinates as $key => $polygon) {
            $coordinates = '';
            foreach ($polygon[0] as $coordinate) {
              $coordinates .= $coordinate[1] . ',' . $coordinate[0] . ' ';
            }
            $position = [
              '#type' => 'geolocation_map_polygon',
              '#coordinates' => $coordinates,
              '#stroke_color' => $settings['stroke_color_randomize'] ? $random_color : $settings['stroke_color'],
              '#stroke_width' => (int) $settings['stroke_width'],
              '#stroke_opacity' => (double) $settings['stroke_opacity'],
              '#fill_color' => $settings['fill_color_randomize'] ? $random_color : $settings['fill_color'],
              '#fill_opacity' => (double) $settings['fill_opacity'],
            ];
            $container[$key] = $position;
          }
          $positions[] = $container;
          break;
        case 'LineString':
          $coordinates = '';
          foreach ($shape->coordinates[0] as $coordinate) {
            $coordinates .= $coordinate[1] . ',' . $coordinate[0] . ' ';
          }
          $position = [
            '#type' => 'geolocation_map_polyline',
            '#coordinates' => $coordinates,
            '#stroke_color' => $settings['stroke_color_randomize'] ? $random_color : $settings['stroke_color'],
            '#stroke_width' => (int) $settings['stroke_width'],
            '#stroke_opacity' => (double) $settings['stroke_opacity'],
          ];
          $positions[] = $position;
          break;
        case 'MultiLineString':
          $container = [
            '#type' => 'container',
            '#attributes' => [
              'class' => [
                'geolocation-multipolyline',
              ],
            ],
          ];
          foreach ($shape->coordinates as $key => $polyline) {
            $coordinates = '';
            foreach ($polyline[0] as $coordinate) {
              $coordinates .= $coordinate[1] . ',' . $coordinate[0] . ' ';
            }
            $position = [
              '#type' => 'geolocation_map_polyline',
              '#coordinates' => $coordinates,
              '#stroke_color' => $settings['stroke_color_randomize'] ? $random_color : $settings['stroke_color'],
              '#stroke_width' => (int) $settings['stroke_width'],
              '#stroke_opacity' => (double) $settings['stroke_opacity'],
            ];
            $container[$key] = $position;
          }
          $positions[] = $container;
          break;
      }
    }
    return $positions;
  }

  /**
   * {@inheritdoc}
   */
  public function getLocationsFromItem(FieldItemInterface $fieldItem) {
    $shapes = $locations = [];
    $this
      ->parseGeoJson($fieldItem
      ->get('geojson')
      ->getString(), $locations, $shapes);
    $positions = [];
    foreach ($locations as $location) {
      switch ($location->type) {
        case 'Point':
          $position = [
            '#type' => 'geolocation_map_location',
            '#coordinates' => [
              'lat' => $location->coordinates[1],
              'lng' => $location->coordinates[0],
            ],
          ];
          $positions[] = $position;
          break;
        case 'MultiPoint':
          $container = [
            '#type' => 'container',
            '#attributes' => [
              'class' => [
                'geolocation-multipoint',
              ],
            ],
          ];
          foreach ($location->coordinates as $key => $point) {
            $position = [
              '#type' => 'geolocation_map_location',
              '#coordinates' => [
                'lat' => $point->coordinates[1],
                'lng' => $point->coordinates[0],
              ],
            ];
            $container[$key] = $position;
          }
          $positions[] = $container;
          break;
      }
    }
    return $positions;
  }

  /**
   * {@inheritdoc}
   */
  public function isFieldGeoOption(FieldDefinitionInterface $fieldDefinition) {
    return in_array($fieldDefinition
      ->getType(), [
      'geolocation_geometry_geometry',
      'geolocation_geometry_geometrycollection',
      'geolocation_geometry_point',
      'geolocation_geometry_linestring',
      'geolocation_geometry_polygon',
      'geolocation_geometry_multipoint',
      'geolocation_geometry_multilinestring',
      'geolocation_geometry_multipolygon',
    ]);
  }

  /**
   * Parse GeoJson for content.
   *
   * @param string $geoJson
   *   GeoJSON.
   * @param array $locations
   *   Locations to be filled.
   * @param array $shapes
   *   Shapes to be filled.
   */
  protected function parseGeoJson(string $geoJson, array &$locations, array &$shapes) {
    $json = json_decode($geoJson);
    if (is_object($json) && isset($json->type)) {
      $json = [
        $json,
      ];
    }
    foreach ($json as $entry) {
      if (empty($entry->type)) {
        continue;
      }
      switch ($entry->type) {
        case 'FeatureCollection':
          if (empty($entry->features)) {
            return;
          }
          $this
            ->parseGeoJson($entry->features, $locations, $shapes);
          return;
        case 'Feature':
          if (empty($entry->geometry)) {
            return;
          }
          $this
            ->parseGeoJson($entry->geometry, $locations, $shapes);
          return;
        case 'GeometryCollection':
          if (empty($entry->geometries)) {
            return;
          }
          $this
            ->parseGeoJson($entry->geometries, $locations, $shapes);
          return;
        case 'MultiPolygon':
        case 'Polygon':
        case 'MultiLineString':
        case 'LineString':
          if (empty($entry->coordinates)) {
            return;
          }
          $shapes[] = $entry;
          return;
        case 'MultiPoint':
        case 'Point':
          if (empty($entry->coordinates)) {
            return;
          }
          $locations[] = $entry;
          return;
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DataProviderBase::$entityFieldManager protected property Entity field manager.
DataProviderBase::$fieldDefinition protected property Field definition.
DataProviderBase::$viewsField protected property Views field.
DataProviderBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 1
DataProviderBase::fieldItemTokens public function Token replacement support function, callback to token replacement function.
DataProviderBase::getFieldItemsFromViewsRow protected function
DataProviderBase::getPositionsFromItem public function Get positions from field item list. Overrides DataProviderInterface::getPositionsFromItem 3
DataProviderBase::getPositionsFromViewsRow public function Get positions from views row. Overrides DataProviderInterface::getPositionsFromViewsRow 1
DataProviderBase::getSettings protected function Add default settings.
DataProviderBase::getTokenHelp public function Return field item tokens. Overrides DataProviderInterface::getTokenHelp 1
DataProviderBase::replaceFieldItemTokens public function Replace field item tokens. Overrides DataProviderInterface::replaceFieldItemTokens 1
DataProviderBase::setFieldDefinition public function Set field definition. Overrides DataProviderInterface::setFieldDefinition
DataProviderBase::setViewsField public function Set views field. Overrides DataProviderInterface::setViewsField
DataProviderBase::__construct public function Constructs a new GeocoderBase object. Overrides PluginBase::__construct 1
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
GeolocationGeometry::defaultSettings protected function Default settings. Overrides DataProviderBase::defaultSettings
GeolocationGeometry::getLocationsFromItem public function Get locations from field item list. Overrides DataProviderBase::getLocationsFromItem
GeolocationGeometry::getLocationsFromViewsRow public function Get locations from views row. Overrides DataProviderBase::getLocationsFromViewsRow
GeolocationGeometry::getSettingsForm public function Provide data provider settings form array. Overrides DataProviderBase::getSettingsForm
GeolocationGeometry::getShapesFromItem public function Get shapes from field item list. Overrides DataProviderBase::getShapesFromItem
GeolocationGeometry::getShapesFromViewsRow public function Get shapes from views row. Overrides DataProviderBase::getShapesFromViewsRow
GeolocationGeometry::isFieldGeoOption public function Determine valid field geo option. Overrides DataProviderInterface::isFieldGeoOption
GeolocationGeometry::isViewsGeoOption public function Determine valid views option. Overrides DataProviderBase::isViewsGeoOption
GeolocationGeometry::parseGeoJson protected function Parse GeoJson for content.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.