You are here

class IpGeoLocPluginStyleOpenLayers in IP Geolocation Views & Maps 8

Views Style plugin extension for OpenLayers (if enabled).

Plugin annotation


@ViewsStyle(
  id = "ip_geoloc_plugin_style_openlayers",
  title = @Translation("Openlayers"),
  help = @Translation("Views Style plugin extension for OpenLayers (if enabled)."),
  theme = "ip_geoloc_openlayers",
  display_types = { "normal" }
)

Hierarchy

Expanded class hierarchy of IpGeoLocPluginStyleOpenLayers

File

src/Plugin/views/style/IpGeoLocPluginStyleOpenLayers.php, line 27

Namespace

Drupal\ip_geoloc\Plugin\views\style
View source
class IpGeoLocPluginStyleOpenLayers extends StylePluginBase implements ContainerFactoryPluginInterface {
  public $moduleHandler;
  public $api;

  /**
   * Constructs a PluginBase object. Adds dependency injection
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, IpGeoLocAPI $api, ModuleHandler $module_handler, IpGeoLocGlobal $ip_geoloc_global, TranslationManager $string_translation, IpGeoLocSession $ip_geoloc_session, IpGeoLocViewsPluginStyle $ip_geoloc_view_plugin_style, RequestStack $request_stack) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->api = $api;
    $this->module_handler = $module_handler;
    $this->ip_geoloc_global = $ip_geoloc_global;
    $this->string_translation = $string_translation;
    $this->session = $ip_geoloc_session;
    $this->view_plugin_style = $ip_geoloc_view_plugin_style;
    $this->request_stack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('ip_geoloc.api'), $container
      ->get('module_handler'), $container
      ->get('ip_geoloc.global'), $container
      ->get('string_translation'), $container
      ->get('ip_geoloc.session'), $container
      ->get('ip_geoloc.views_plugin_style'), $container
      ->get('request_stack'));
  }

  /**
   * Set default Leaflet options.
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $latitude = $this->moduleHandler
      ->moduleExists('location') ? 'location_latitude' : 'ip_geoloc_latitude';

    // For field-based modules.
    $longitude = $this->moduleHandler
      ->moduleExists('location') ? 'location_longitude' : ($latitude == 'ip_geoloc_latitude' ? 'ip_geoloc_longitude' : $latitude);
    $options['ip_geoloc_views_plugin_latitude'] = [
      'default' => $latitude,
    ];
    $options['ip_geoloc_views_plugin_longitude'] = [
      'default' => $longitude,
    ];
    $options['differentiator'] = [
      'contains' => [
        'differentiator_field' => [
          'default' => '',
        ],
      ],
    ];
    $options['default_marker_color'] = [
      'default' => '',
    ];
    $options['center_option'] = [
      'default' => IP_GEOLOC_MAP_CENTER_ON_FIRST_LOCATION,
    ];
    $options['argument'] = [
      'default' => '',
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $form['map'] = [
      '#type' => 'select',
      '#title' => t('Map'),
      '#description' => t('The OpenLayers map used to place the view locations on. You can configure map and markers <a href="/admin/structure/openlayers/maps">here</a>.'),
      '#options' => openlayers_map_options(),
      '#default_value' => isset($this->options['map']) ? $this->options['map'] : \Drupal::state()
        ->get('openlayers_default_map', 'default'),
    ];
    $form_state
      ->set('renderer', 'openlayers');
    $this->view_plugin_style
      ->pluginStyleBulkOfForm($this, $form, $form_state);

    // OpenLayers has "Hide empty map for Views" for this.
    unset($form['empty_map_center']);
    $form['center_option']['#options'][IP_GEOLOC_MAP_CENTER_ON_LOCATION_FROM_ARGUMENT] = t('Use lat/lon coordinate arguments from a contextual filter');
    $argument_handlers = $this->view->display_handler
      ->get_handlers('argument');
    if (!empty($argument_handlers)) {
      $argument_options = [
        '' => '<' . t('none') . '>',
      ];
      foreach ($argument_handlers as $key => $handler) {
        $argument_options[$key] = $handler->definition['group'] . ': ' . $handler->definition['title'];
      }
      $form['argument'] = [
        '#type' => 'select',
        '#title' => t('Choose a contextual filter to pull data from'),
        '#options' => $argument_options,
        '#default_value' => $this->options['argument'],
        '#weight' => 100,
      ];
    }
  }

  /**
   * Validate the options form.
   */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    $this->view_plugin_style
      ->pluginStyleBulkOfFormValidate($form, $form_state);
  }

  /**
   * Transform the View result in a list of markers and render these on a map.
   */
  public function render() {

    // This somewhat mimics function openlayers_render_map_data() and class
    // openlayers_views_style_map, function render()
    $map = openlayers_map_load(isset($this->options['map']) ? $this->options['map'] : \Drupal::state()
      ->get('openlayers_default_map', 'default'));

    // Function openlayers_build_map() invokes:
    // - hook_openlayers_map_preprocess_alter(&$map), which introduces the names
    //   of the layers we'll use: IP_GEOLOC_MARKER_LAYER_1..3 and
    //   IP_GEOLOC_VISITOR_MARKER_LAYER
    // - hook_openlayers_layers(), which creates barebone layers for the above
    // - hook_openlayers_map_alter(&$map), for modules to make final changes to
    //   the map and its layers.
    $map = openlayers_build_map($map->data);

    // Return themed map if no errors found.
    if (empty($map['errors'])) {
      ip_geoloc_plugin_style_render_fields($this);
      $locations = ip_geoloc_plugin_style_extract_locations($this);
      $center_option = !isset($this->options['center_option']) ? IP_GEOLOC_MAP_CENTER_ON_FIRST_LOCATION : $this->options['center_option'];
      $visitor_location = $this->api
        ->getVisitorLocation();
      if ($center_option == IP_GEOLOC_MAP_CENTER_ON_VISITOR && ($center_set = isset($visitor_location['longitude']))) {
        $longitude = $visitor_location['longitude'];
        $latitude = $visitor_location['latitude'];
        $map['center']['initial']['centerpoint'] = "{$longitude},{$latitude}";
      }
      elseif (($center_option == IP_GEOLOC_MAP_CENTER_OF_LOCATIONS || $center_option == IP_GEOLOC_MAP_CENTER_OF_LOCATIONS_WEIGHTED) && !empty($locations)) {
        list($latitude, $longitude) = ip_geoloc_center_of_locations($locations, $center_option == IP_GEOLOC_MAP_CENTER_OF_LOCATIONS_WEIGHTED);
        $map['center']['initial']['centerpoint'] = "{$longitude},{$latitude}";
        $center_set = TRUE;
      }
      elseif ($center_option == IP_GEOLOC_MAP_CENTER_ON_LOCATION_FROM_ARGUMENT) {
        if ($handler = $this->view->display_handler
          ->get_handler('argument', $this->options['argument'])) {
          $latitude = $handler->value['lat'];
          $longitude = $handler->value['lon'];
          $map['center']['initial']['centerpoint'] = "{$longitude},{$latitude}";
          $center_set = TRUE;
        }
      }
      foreach ($locations as $location) {
        if (isset($location->lon)) {
          $lon = $location->lon;
          $lat = $location->lat;
        }
        elseif (isset($location->longitude)) {
          $lon = $location->longitude;
          $lat = $location->latitude;
        }
        else {
          continue;
        }
        if (empty($center_set) && $center_option == IP_GEOLOC_MAP_CENTER_ON_FIRST_LOCATION) {
          $map['center']['initial']['centerpoint'] = "{$lon},{$lat}";
          $center_set = TRUE;
        }
        $feature = [
          // Only 'name' and 'description' are valid attribute names.
          // @see openlayers_behavior_popup.js
          'attributes' => [
            'description' => $location->balloon_text,
          ],
          'projection' => 'EPSG:4326',
          'wkt' => "POINT({$lon} {$lat})",
        ];
        $layer = isset($location->marker_color) && is_numeric($location->marker_color) ? $location->marker_color : 1;
        $map['layers'][IP_GEOLOC_MARKER_LAYER . $layer]['features'][] = $feature;
      }

      // See admin/structure/openlayers/maps/<map-name>/edit...
      // If "Hide empty map for Views" is ticked, then if the map has no
      // features, it should not be displayed.
      if (!empty($map['hide_empty_map'])) {
        $num_location_marker_layers = \Drupal::state()
          ->get('ip_geoloc_num_location_marker_layers', IP_GEOLOC_DEF_NUM_MARKER_LAYERS);
        for ($layer = 1; $layer <= $num_location_marker_layers; $layer++) {
          if (!empty($map['layers'][IP_GEOLOC_MARKER_LAYER . $layer]['features'])) {
            $some_location_layers = TRUE;
            break;
          }
        }
        if (empty($some_location_layers) && empty($map['layers'][IP_GEOLOC_VISITOR_MARKER_LAYER]['features'])) {

          // Nothing to show.
          return '';
        }
      }
      $js = [
        'openlayers' => [
          'maps' => [
            $map['id'] => $map,
          ],
        ],
      ];
      drupal_add_js($js, 'setting');

      // Unlike openlayers.theme.inc, theme_openlayers_map(), we use a template.
      //
      // To ensure that any controls are on the map correctly, we need to
      // wrap the map in a container, and take into account %-dimensions.
      $container_width = $map['width'];
      $container_height = $map['height'];
      $map['width'] = strpos($map['width'], '%') > 0 ? '100%' : $map['width'];
      $map['height'] = strpos($map['height'], '%') > 0 ? '100%' : $map['height'];

      // Uses ip-geoloc-openlayers.tpl.php.
      $output = theme([
        'ip_geoloc_openlayers',
      ], [
        'view' => $this->view,
        // 'options' => $this->options,.
        'map' => $map,
        'container_width' => $container_width,
        'container_height' => $container_height,
      ]);
    }
    else {
      $output = implode('<br/>', $map['errors']);
    }
    return $output;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
IpGeoLocPluginStyleOpenLayers::$api public property
IpGeoLocPluginStyleOpenLayers::$moduleHandler public property
IpGeoLocPluginStyleOpenLayers::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides StylePluginBase::buildOptionsForm
IpGeoLocPluginStyleOpenLayers::create public static function Creates an instance of the plugin. Overrides PluginBase::create
IpGeoLocPluginStyleOpenLayers::defineOptions protected function Set default Leaflet options. Overrides StylePluginBase::defineOptions
IpGeoLocPluginStyleOpenLayers::render public function Transform the View result in a list of markers and render these on a map. Overrides StylePluginBase::render
IpGeoLocPluginStyleOpenLayers::validateOptionsForm public function Validate the options form. Overrides StylePluginBase::validateOptionsForm
IpGeoLocPluginStyleOpenLayers::__construct public function Constructs a PluginBase object. Adds dependency injection Overrides PluginBase::__construct
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::$definition public property Plugins's definition
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$view public property The top object of a view. 1
PluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 14
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
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::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::submitOptionsForm public function Handle any special handling on the validate form. Overrides ViewsPluginInterface::submitOptionsForm 16
PluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides ViewsPluginInterface::summaryTitle 6
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
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.
StylePluginBase::$defaultFieldLabels protected property Should field labels be enabled by default. 1
StylePluginBase::$groupingTheme protected property The theme function used to render the grouping set.
StylePluginBase::$rendered_fields protected property Stores the rendered field values, keyed by the row index and field name.
StylePluginBase::$rowTokens protected property Store all available tokens row rows.
StylePluginBase::$usesFields protected property Does the style plugin for itself support to add fields to its output. 3
StylePluginBase::$usesGrouping protected property Does the style plugin support grouping of rows. 3
StylePluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. Overrides PluginBase::$usesOptions
StylePluginBase::$usesRowClass protected property Does the style plugin support custom css class for the rows. 3
StylePluginBase::$usesRowPlugin protected property Whether or not this style uses a row plugin. 10
StylePluginBase::buildSort public function Called by the view builder to see if this style handler wants to interfere with the sorts. If so it should build; if it returns any non-TRUE value, normal sorting will NOT be added to the query. 1
StylePluginBase::buildSortPost public function Called by the view builder to let the style build a second set of sorts that will come after any other sorts in the view. 1
StylePluginBase::defaultFieldLabels public function Return TRUE if this style enables field labels by default. 1
StylePluginBase::destroy public function Clears a plugin. Overrides PluginBase::destroy
StylePluginBase::elementPreRenderRow public function #pre_render callback for view row field rendering.
StylePluginBase::evenEmpty public function Should the output of the style plugin be rendered even if it's a empty view. 2
StylePluginBase::getField public function Gets a rendered field.
StylePluginBase::getFieldValue public function Get the raw field value.
StylePluginBase::getRowClass public function Return the token replaced row class for the specified row.
StylePluginBase::init public function Overrides \Drupal\views\Plugin\views\PluginBase::init(). Overrides PluginBase::init
StylePluginBase::preRender public function Allow the style to do stuff before each row is rendered.
StylePluginBase::query public function Add anything to the query that we might need to. Overrides PluginBase::query 1
StylePluginBase::renderFields protected function Renders all of the fields for a given style and store them on the object.
StylePluginBase::renderGrouping public function Group records as needed for rendering.
StylePluginBase::renderGroupingSets public function Render the grouping sets.
StylePluginBase::renderRowGroup protected function Renders a group of rows of the grouped view.
StylePluginBase::tokenizeValue public function Take a value and apply token replacement logic to it.
StylePluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides PluginBase::trustedCallbacks
StylePluginBase::usesFields public function Return TRUE if this style also uses fields. 3
StylePluginBase::usesGrouping public function Returns the usesGrouping property. 3
StylePluginBase::usesRowClass public function Returns the usesRowClass property. 3
StylePluginBase::usesRowPlugin public function Returns the usesRowPlugin property. 10
StylePluginBase::usesTokens public function Return TRUE if this style uses tokens.
StylePluginBase::validate public function Validate that the plugin is correct and can be saved. Overrides PluginBase::validate
StylePluginBase::wizardForm public function Provide a form in the views wizard if this style is selected.
StylePluginBase::wizardSubmit public function Alter the options of a display before they are added to the view. 1
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.