You are here

class CommonMap in Geolocation Field 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/views/style/CommonMap.php \Drupal\geolocation\Plugin\views\style\CommonMap

Allow to display several field items on a common map.

Plugin annotation


@ViewsStyle(
  id = "maps_common",
  title = @Translation("Geolocation Google Maps API - CommonMap"),
  help = @Translation("Display geolocations on a common map."),
  theme = "views_view_list",
  display_types = {"normal"},
)

Hierarchy

Expanded class hierarchy of CommonMap

1 string reference to 'CommonMap'
views.view.geolocation_demo_common_map.yml in modules/geolocation_demo/config/optional/views.view.geolocation_demo_common_map.yml
modules/geolocation_demo/config/optional/views.view.geolocation_demo_common_map.yml

File

src/Plugin/views/style/CommonMap.php, line 26

Namespace

Drupal\geolocation\Plugin\views\style
View source
class CommonMap extends StylePluginBase {
  use GoogleMapsDisplayTrait;
  protected $usesFields = TRUE;
  protected $usesRowPlugin = TRUE;
  protected $usesRowClass = FALSE;
  protected $usesGrouping = FALSE;

  /**
   * Map update option handling.
   *
   * Dynamic map and client location and potentially others update the view by
   * information determined on the client site. They may want to update the
   * view result as well. So we need to provide the possible ways to do that.
   *
   * @return array
   *   The determined options.
   */
  protected function getMapUpdateOptions() {
    $options = [
      'boundary_filters' => [],
      'boundary_filters_exposed' => [],
      'map_update_options' => [],
    ];
    $filters = $this->displayHandler
      ->getOption('filters');
    foreach ($filters as $filter_name => $filter) {
      if (empty($filter['plugin_id'])) {
        continue;
      }

      /** @var \Drupal\views\Plugin\views\filter\FilterPluginBase $filter_handler */
      $filter_handler = $this->displayHandler
        ->getHandler('filter', $filter_name);
      switch ($filter['plugin_id']) {
        case 'geolocation_filter_boundary':
          if ($filter_handler
            ->isExposed()) {
            $options['boundary_filters_exposed'][$filter_name] = $filter_handler;
          }
          break;
      }
    }
    foreach ($options['boundary_filters_exposed'] as $filter_name => $filter_handler) {
      $options['map_update_options']['boundary_filter_' . $filter_name] = $this
        ->t('Boundary Filter') . ' - ' . $filter_handler
        ->adminLabel();
    }
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function evenEmpty() {
    return $this->options['even_empty'] ? TRUE : FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    if (!empty($this->options['geolocation_field'])) {
      $geo_field = $this->options['geolocation_field'];
    }
    else {
      \Drupal::logger('geolocation')
        ->error("The geolocation common map views style was called without a geolocation field defined in the views style settings.");
      return [];
    }
    if (!empty($this->options['title_field']) && $this->options['title_field'] != 'none') {
      $title_field = $this->options['title_field'];
    }
    if (!empty($this->options['icon_field']) && $this->options['icon_field'] != 'none') {
      $icon_field = $this->options['icon_field'];
    }
    if (!empty($this->options['marker_scroll_to_result']) && !empty($this->options['id_field']) && $this->options['id_field'] != 'none') {
      $id_field = $this->options['id_field'];
    }
    $map_id = $this->view->dom_id;
    $build = [
      '#theme' => $this->view
        ->buildThemeFunctions('geolocation_common_map_display'),
      '#view' => $this->view,
      '#id' => $map_id,
      '#attached' => [
        'library' => [
          'geolocation/geolocation.commonmap',
        ],
        'drupalSettings' => [
          'geolocation' => [
            'commonMap' => [
              $map_id => [
                'settings' => $this
                  ->getGoogleMapsSettings($this->options),
              ],
            ],
            'google_map_url' => $this
              ->getGoogleMapsApiUrl(),
          ],
        ],
      ],
    ];

    // Add cache dependency for the view.
    $renderer = $this
      ->getRenderer();
    $renderer
      ->addCacheableDependency($build, $this->view->storage);
    if (!empty($this->options['show_raw_locations'])) {
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['showRawLocations'] = TRUE;
    }

    /*
     * Context popup content.
     */
    if (!empty($this->options['context_popup_content'])) {
      $context_popup_content = \Drupal::token()
        ->replace($this->options['context_popup_content']);
      $context_popup_content = PlainTextOutput::renderFromHtml($context_popup_content);
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['contextPopupContent'] = [];
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['contextPopupContent']['enable'] = TRUE;
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['contextPopupContent']['content'] = $context_popup_content;
    }

    /*
     * Marker clusterer.
     */
    if (!empty($this->options['marker_clusterer'])) {
      $build['#attached']['library'][] = 'geolocation/geolocation.markerclusterer';
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['markerClusterer'] = [];
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['markerClusterer']['enable'] = TRUE;
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['markerClusterer']['imagePath'] = $this->options['marker_clusterer_image_path'];
      if (!empty($this->options['marker_clusterer_styles'])) {
        $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['markerClusterer']['styles'] = json_decode($this->options['marker_clusterer_styles']);
      }
    }

    /*
     * Dynamic map handling.
     */
    if (!empty($this->options['dynamic_map']['enabled'])) {
      if (!empty($this->options['dynamic_map']['update_target']) && $this->view->displayHandlers
        ->has($this->options['dynamic_map']['update_target'])) {
        $update_view_display_id = $this->options['dynamic_map']['update_target'];
      }
      else {
        $update_view_display_id = $this->view->current_display;
      }
      $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['dynamic_map'] = [
        'enable' => TRUE,
        'hide_form' => $this->options['dynamic_map']['hide_form'],
        'views_refresh_delay' => $this->options['dynamic_map']['views_refresh_delay'],
        'update_view_id' => $this->view
          ->id(),
        'update_view_display_id' => $update_view_display_id,
      ];
      if (substr($this->options['dynamic_map']['update_handler'], 0, strlen('boundary_filter_')) === 'boundary_filter_') {
        $filter_id = substr($this->options['dynamic_map']['update_handler'], strlen('boundary_filter_'));
        $filters = $this->displayHandler
          ->getOption('filters');
        $filter_options = $filters[$filter_id];
        $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['dynamic_map'] += [
          'boundary_filter' => TRUE,
          'parameter_identifier' => $filter_options['expose']['identifier'],
        ];
      }
    }
    $this
      ->renderFields($this->view->result);

    /*
     * Add locations to output.
     */
    foreach ($this->view->result as $row_number => $row) {
      if (!empty($title_field)) {
        if (!empty($this->rendered_fields[$row_number][$title_field])) {
          $title_build = $this->rendered_fields[$row_number][$title_field];
        }
        elseif (!empty($this->view->field[$title_field])) {
          $title_build = $this->view->field[$title_field]
            ->render($row);
        }
      }
      if ($this->view->field[$geo_field] instanceof GeolocationField) {

        /** @var \Drupal\geolocation\Plugin\views\field\GeolocationField $geolocation_field */
        $geolocation_field = $this->view->field[$geo_field];
        $entity = $geolocation_field
          ->getEntity($row);
        if (isset($entity->{$geolocation_field->definition['field_name']})) {

          /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
          $geo_items = $entity->{$geolocation_field->definition['field_name']};
        }
        else {
          $geo_items = [];
        }
      }
      else {
        return $build;
      }
      if (!empty($id_field)) {
        $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['markerScrollToResult'] = TRUE;

        /** @var \Drupal\views\Plugin\views\field\Field $id_field_handler */
        $id_field_handler = $this->view->field[$id_field];
        if (!empty($id_field_handler)) {
          $location_id = $id_field_handler
            ->getValue($row);
        }
      }
      $icon_url = NULL;
      if (!empty($icon_field)) {

        /** @var \Drupal\views\Plugin\views\field\Field $icon_field_handler */
        $icon_field_handler = $this->view->field[$icon_field];
        if (!empty($icon_field_handler)) {
          $image_items = $icon_field_handler
            ->getItems($row);
          if (!empty($image_items[0]['rendered']['#item']->entity)) {
            $file_uri = $image_items[0]['rendered']['#item']->entity
              ->getFileUri();
            $style = NULL;
            if (!empty($image_items[0]['rendered']['#image_style'])) {

              /** @var \Drupal\image\Entity\ImageStyle $style */
              $style = ImageStyle::load($image_items[0]['rendered']['#image_style']);
            }
            if (!empty($style)) {
              $icon_url = file_url_transform_relative($style
                ->buildUrl($file_uri));
            }
            else {
              $icon_url = file_url_transform_relative(file_create_url($file_uri));
            }
          }
        }
      }

      /** @var \Drupal\geolocation\Plugin\Field\FieldType\GeolocationItem $item */
      foreach ($geo_items as $delta => $item) {
        $position = [
          'lat' => $item
            ->get('lat')
            ->getValue(),
          'lng' => $item
            ->get('lng')
            ->getValue(),
        ];
        $location = [
          '#theme' => 'geolocation_common_map_location',
          '#content' => $this->view->rowPlugin
            ->render($row),
          '#title' => empty($title_build) ? '' : $title_build,
          '#position' => $position,
        ];
        if (!empty($icon_url)) {
          $location['#icon'] = $icon_url;
        }
        else {
          if (!empty($this->options['google_map_settings']['marker_icon_path']) && !empty($this->rowTokens[$row_number])) {
            $icon_token_uri = $this
              ->viewsTokenReplace($this->options['google_map_settings']['marker_icon_path'], $this->rowTokens[$row_number]);
            $icon_token_url = file_create_url(trim($icon_token_uri));
            if ($icon_token_url) {
              $location['#icon'] = $icon_token_url;
            }
            else {
              try {
                $icon_token_url = Url::fromUri($icon_token_uri);
                if ($icon_token_url) {
                  $location['#icon'] = $icon_token_url
                    ->setAbsolute(TRUE)
                    ->toString();
                }
              } catch (\Exception $e) {

                // User entered mal-formed URL, but that doesn't matter.
                // We hereby skip it anyway.
              }
            }
          }
        }
        if (!empty($location_id)) {
          $location['#location_id'] = $location_id;
        }
        if ($this->options['marker_row_number']) {
          $location['#marker_label'] = (int) $row_number + 1;
        }
        $build['#locations'][] = $location;
      }
    }
    $centre = NULL;
    $fitbounds = FALSE;

    // Maps will not load without any centre defined.
    if (!is_array($this->options['centre'])) {
      return $build;
    }

    /*
     * Centre handling.
     */
    foreach ($this->options['centre'] as $id => $option) {

      // Ignore if not enabled.
      if (empty($option['enable'])) {
        continue;
      }

      // Break if fitBounds is enabled, as it will supersede any other option.
      if ($fitbounds) {
        break;
      }
      elseif (isset($centre['lat']) && isset($centre['lng'])) {
        break;
      }
      elseif (isset($centre['lat_north_east']) && isset($centre['lng_north_east']) && isset($centre['lat_south_west']) && isset($centre['lng_south_west'])) {
        break;
      }
      switch ($id) {
        case 'fixed_value':
          $centre = [
            'lat' => (double) $option['settings']['latitude'],
            'lng' => (double) $option['settings']['longitude'],
          ];
          break;
        case 'first_row':
          if (!empty($build['#locations'][0]['#position'])) {
            $centre = $build['#locations'][0]['#position'];
          }
          break;
        case 'fit_bounds':

          // fitBounds will only work when at least one result is available.
          if (!empty($build['#locations'][0]['#position'])) {
            $fitbounds = TRUE;
          }
          break;
        case 'client_location':
          $build['#clientlocation'] = TRUE;
          $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['client_location'] = [
            'enable' => TRUE,
          ];
          if ($option['settings']['update_map']) {
            $build['#attached']['drupalSettings']['geolocation']['commonMap'][$map_id]['client_location']['update_map'] = TRUE;
          }
          break;

        /*
         * Handle the dynamic options.
         */
        default:
          if (preg_match('/proximity_filter_*/', $id)) {
            $filter_id = substr($id, 17);

            /** @var \Drupal\geolocation\Plugin\views\filter\ProximityFilter $handler */
            $handler = $this->displayHandler
              ->getHandler('filter', $filter_id);
            if (isset($handler->value['lat']) && isset($handler->value['lng'])) {
              $centre = [
                'lat' => (double) $handler
                  ->getLatitudeValue(),
                'lng' => (double) $handler
                  ->getLongitudeValue(),
              ];
            }
            break;
          }
          elseif (preg_match('/boundary_filter_*/', $id)) {
            $filter_id = substr($id, 16);

            /** @var \Drupal\geolocation\Plugin\views\filter\ProximityFilter $handler */
            $handler = $this->displayHandler
              ->getHandler('filter', $filter_id);
            if (isset($handler->value['lat_north_east']) && $handler->value['lat_north_east'] !== "" && isset($handler->value['lng_north_east']) && $handler->value['lng_north_east'] !== "" && isset($handler->value['lat_south_west']) && $handler->value['lat_south_west'] !== "" && isset($handler->value['lng_south_west']) && $handler->value['lng_south_west'] !== "") {
              $centre = [
                'lat_north_east' => (double) $handler->value['lat_north_east'],
                'lng_north_east' => (double) $handler->value['lng_north_east'],
                'lat_south_west' => (double) $handler->value['lat_south_west'],
                'lng_south_west' => (double) $handler->value['lng_south_west'],
              ];
            }
            break;
          }
      }
    }
    if (!empty($centre)) {
      $build['#centre'] = $centre ?: [
        'lat' => 0,
        'lng' => 0,
      ];
    }
    $build['#fitbounds'] = $fitbounds;
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['show_raw_locations'] = [
      'default' => '0',
    ];
    $options['even_empty'] = [
      'default' => '0',
    ];
    $options['geolocation_field'] = [
      'default' => '',
    ];
    $options['title_field'] = [
      'default' => '',
    ];
    $options['icon_field'] = [
      'default' => '',
    ];
    $options['marker_scroll_to_result'] = [
      'default' => 0,
    ];
    $options['marker_row_number'] = [
      'default' => FALSE,
    ];
    $options['id_field'] = [
      'default' => '',
    ];
    $options['marker_clusterer'] = [
      'default' => 0,
    ];
    $options['marker_clusterer_image_path'] = [
      'default' => '',
    ];
    $options['marker_clusterer_styles'] = [
      'default' => [],
    ];
    $options['dynamic_map'] = [
      'contains' => [
        'enabled' => [
          'default' => 0,
        ],
        'update_handler' => [
          'default' => '',
        ],
        'update_target' => [
          'default' => '',
        ],
        'hide_form' => [
          'default' => 0,
        ],
        'views_refresh_delay' => [
          'default' => '1200',
        ],
      ],
    ];
    $options['centre'] = [
      'default' => '',
    ];
    $options['context_popup_content'] = [
      'default' => '',
    ];
    foreach (self::getGoogleMapDefaultSettings() as $key => $setting) {
      $options[$key] = [
        'default' => $setting,
      ];
    }
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $labels = $this->displayHandler
      ->getFieldLabels();
    $fieldMap = \Drupal::service('entity_field.manager')
      ->getFieldMap();
    $geo_options = [];
    $title_options = [];
    $icon_options = [];
    $id_options = [];
    $fields = $this->displayHandler
      ->getOption('fields');
    foreach ($fields as $field_name => $field) {
      if ($field['plugin_id'] == 'geolocation_field') {
        $geo_options[$field_name] = $labels[$field_name];
      }
      if ($field['plugin_id'] == 'field' && !empty($field['entity_type']) && !empty($field['entity_field'])) {
        if (!empty($fieldMap[$field['entity_type']][$field['entity_field']]['type']) && $fieldMap[$field['entity_type']][$field['entity_field']]['type'] == 'geolocation') {
          $geo_options[$field_name] = $labels[$field_name];
        }
      }
      if (!empty($field['type']) && $field['type'] == 'image') {
        $icon_options[$field_name] = $labels[$field_name];
      }
      if (!empty($field['type']) && $field['type'] == 'string') {
        $title_options[$field_name] = $labels[$field_name];
      }
      if (!empty($field['type']) && $field['type'] == 'number_integer') {
        $id_options[$field_name] = $labels[$field_name];
      }
    }
    $form['geolocation_field'] = [
      '#title' => $this
        ->t('Geolocation source field'),
      '#type' => 'select',
      '#default_value' => $this->options['geolocation_field'],
      '#description' => $this
        ->t("The source of geodata for each entity."),
      '#options' => $geo_options,
      '#required' => TRUE,
    ];
    $form['title_field'] = [
      '#title' => $this
        ->t('Title source field'),
      '#type' => 'select',
      '#default_value' => $this->options['title_field'],
      '#description' => $this
        ->t("The source of the title for each entity. Field type must be 'string'."),
      '#options' => $title_options,
      '#empty_value' => 'none',
    ];
    $map_update_target_options = $this
      ->getMapUpdateOptions();

    /*
     * Dynamic map handling.
     */
    if (!empty($map_update_target_options['map_update_options'])) {
      $form['dynamic_map'] = [
        '#title' => $this
          ->t('Dynamic Map'),
        '#type' => 'fieldset',
      ];
      $form['dynamic_map']['enabled'] = [
        '#title' => $this
          ->t('Update view on map boundary changes. Also known as "AirBnB" style.'),
        '#type' => 'checkbox',
        '#default_value' => $this->options['dynamic_map']['enabled'],
        '#description' => $this
          ->t("If enabled, moving the map will filter results based on current map boundary. This functionality requires an exposed boundary filter. Enabling AJAX is highly recommend for best user experience. If additional views are to be updated with the map change as well, it is highly recommended to use the view containing the map as 'parent' and the additional views as attachments."),
      ];
      $form['dynamic_map']['update_handler'] = [
        '#title' => $this
          ->t('Dynamic map update handler'),
        '#type' => 'select',
        '#default_value' => $this->options['dynamic_map']['update_handler'],
        '#description' => $this
          ->t("The map has to know how to feed back the update boundary data to the view."),
        '#options' => $map_update_target_options['map_update_options'],
        '#states' => [
          'visible' => [
            ':input[name="style_options[dynamic_map][enabled]"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
      $form['dynamic_map']['hide_form'] = [
        '#title' => $this
          ->t('Hide exposed filter form element if applicable.'),
        '#type' => 'checkbox',
        '#default_value' => $this->options['dynamic_map']['hide_form'],
        '#states' => [
          'visible' => [
            ':input[name="style_options[dynamic_map][enabled]"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
      $form['dynamic_map']['views_refresh_delay'] = [
        '#title' => $this
          ->t('Minimum idle time in milliseconds required to trigger views refresh'),
        '#description' => $this
          ->t('Once the view refresh is triggered, any further change of the map bounds will have no effect until the map update is finished. User interactions like scrolling in and out or dragging the map might trigger the map idle event, before the user is finished interacting. This setting adds a delay before the view is refreshed to allow further map interactions.'),
        '#type' => 'number',
        '#min' => 0,
        '#default_value' => $this->options['dynamic_map']['views_refresh_delay'],
        '#states' => [
          'visible' => [
            ':input[name="style_options[dynamic_map][enabled]"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
      if ($this->displayHandler
        ->getPluginId() !== 'page') {
        $update_targets = [
          $this->displayHandler->display['id'] => $this
            ->t('- This display -'),
        ];
        foreach ($this->view->displayHandlers
          ->getInstanceIds() as $instance_id) {
          $display_instance = $this->view->displayHandlers
            ->get($instance_id);
          if ($display_instance
            ->getPluginId() == 'page') {
            $update_targets[$instance_id] = $display_instance->display['display_title'];
          }
        }
        if (!empty($update_targets)) {
          $form['dynamic_map']['update_target'] = [
            '#title' => $this
              ->t('Dynamic map update target'),
            '#type' => 'select',
            '#default_value' => $this->options['dynamic_map']['update_target'],
            '#description' => $this
              ->t("Non-page displays will only update themselves. Most likely a page view should be updated instead."),
            '#options' => $update_targets,
            '#states' => [
              'visible' => [
                ':input[name="style_options[dynamic_map][enabled]"]' => [
                  'checked' => TRUE,
                ],
              ],
            ],
          ];
        }
      }
    }

    /*
     * Centre handling.
     */
    $options = [
      'fit_bounds' => $this
        ->t('Automatically fit map bounds to results. Disregards any set center or zoom.'),
      'first_row' => $this
        ->t('Use first row as centre.'),
      'fixed_value' => $this
        ->t('Provide fixed latitude and longitude.'),
      'client_location' => $this
        ->t('Ask client for location via HTML5 geolocation API.'),
    ];
    $options += $map_update_target_options['map_update_options'];
    $form['centre'] = [
      '#type' => 'table',
      '#prefix' => $this
        ->t('<h3>Centre options</h3>Please note: Each option will, if it can be applied, supersede any following option.'),
      '#header' => [
        $this
          ->t('Enable'),
        $this
          ->t('Option'),
        $this
          ->t('settings'),
        [
          'data' => $this
            ->t('Settings'),
          'colspan' => '1',
        ],
      ],
      '#attributes' => [
        'id' => 'geolocation-centre-options',
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'geolocation-centre-option-weight',
        ],
      ],
    ];
    foreach ($options as $id => $label) {
      $weight = isset($this->options['centre'][$id]['weight']) ? $this->options['centre'][$id]['weight'] : 0;
      $form['centre'][$id]['#weight'] = $weight;
      $form['centre'][$id]['enable'] = [
        '#type' => 'checkbox',
        '#default_value' => isset($this->options['centre'][$id]['enable']) ? $this->options['centre'][$id]['enable'] : TRUE,
      ];
      $form['centre'][$id]['option'] = [
        '#markup' => $label,
      ];

      // Add tabledrag supprt.
      $form['centre'][$id]['#attributes']['class'][] = 'draggable';
      $form['centre'][$id]['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight for @option', [
          '@option' => $label,
        ]),
        '#title_display' => 'invisible',
        '#size' => 4,
        '#default_value' => $weight,
        '#attributes' => [
          'class' => [
            'geolocation-centre-option-weight',
          ],
        ],
      ];
    }
    $form['centre']['client_location']['settings'] = [
      '#type' => 'container',
      'update_map' => [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Additionally feed clients location back to view via dynamic map settings?'),
        '#default_value' => isset($this->options['centre']['client_location']['settings']['update_map']) ? $this->options['centre']['client_location']['settings']['update_map'] : FALSE,
      ],
      '#states' => [
        'visible' => [
          ':input[name="style_options[centre][client_location][enable]"]' => [
            'checked' => TRUE,
          ],
          ':input[name="style_options[dynamic_map][enabled]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['centre']['fixed_value']['settings'] = [
      '#type' => 'container',
      'latitude' => [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Latitude'),
        '#default_value' => isset($this->options['centre']['fixed_value']['settings']['latitude']) ? $this->options['centre']['fixed_value']['settings']['latitude'] : '',
        '#size' => 60,
        '#maxlength' => 128,
      ],
      'longitude' => [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Longitude'),
        '#default_value' => isset($this->options['centre']['fixed_value']['settings']['longitude']) ? $this->options['centre']['fixed_value']['settings']['longitude'] : '',
        '#size' => 60,
        '#maxlength' => 128,
      ],
      '#states' => [
        'visible' => [
          ':input[name="style_options[centre][fixed_value][enable]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    uasort($form['centre'], 'Drupal\\Component\\Utility\\SortArray::sortByWeightProperty');

    /*
     * Advanced settings
     */
    $form['advanced_settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Advanced settings'),
    ];
    $form['show_raw_locations'] = [
      '#group' => 'style_options][advanced_settings',
      '#title' => $this
        ->t('Show raw locations'),
      '#description' => $this
        ->t('By default, the location data for the map will be hidden when the map loads.'),
      '#type' => 'checkbox',
      '#default_value' => $this->options['show_raw_locations'],
    ];
    $form['even_empty'] = [
      '#group' => 'style_options][advanced_settings',
      '#title' => $this
        ->t('Display map when no locations are found'),
      '#type' => 'checkbox',
      '#default_value' => $this->options['even_empty'],
    ];
    if ($icon_options) {
      $form['icon_field'] = [
        '#group' => 'style_options][advanced_settings',
        '#title' => $this
          ->t('Icon source field'),
        '#type' => 'select',
        '#default_value' => $this->options['icon_field'],
        '#description' => $this
          ->t("Optional image (field) to use as icon."),
        '#options' => $icon_options,
        '#empty_value' => 'none',
        '#process' => [
          [
            '\\Drupal\\Core\\Render\\Element\\RenderElement',
            'processGroup',
          ],
          [
            '\\Drupal\\Core\\Render\\Element\\Select',
            'processSelect',
          ],
        ],
        '#pre_render' => [
          [
            '\\Drupal\\Core\\Render\\Element\\RenderElement',
            'preRenderGroup',
          ],
        ],
      ];
    }
    if ($id_options) {
      $form['marker_scroll_to_result'] = [
        '#group' => 'style_options][advanced_settings',
        '#title' => $this
          ->t('On clicking marker scroll to result instead of opening marker bubble'),
        '#type' => 'checkbox',
        '#default_value' => $this->options['marker_scroll_to_result'],
      ];
      $form['id_field'] = [
        '#group' => 'style_options][advanced_settings',
        '#title' => $this
          ->t('ID source field'),
        '#type' => 'select',
        '#default_value' => $this->options['id_field'],
        '#description' => $this
          ->t("Unique location ID used as scrolling target. If not targeting the raw location output, either add a class structured as 'geolocation-location-id-[ID]' or an attribute 'data-location-id=\"[ID]\"' to the target element."),
        '#options' => $id_options,
        '#empty_value' => 'none',
        '#states' => [
          'visible' => [
            ':input[name="style_options[marker_scroll_to_result]"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
        '#process' => [
          [
            '\\Drupal\\Core\\Render\\Element\\RenderElement',
            'processGroup',
          ],
          [
            '\\Drupal\\Core\\Render\\Element\\Select',
            'processSelect',
          ],
        ],
        '#pre_render' => [
          [
            '\\Drupal\\Core\\Render\\Element\\RenderElement',
            'preRenderGroup',
          ],
        ],
      ];
    }
    $form['marker_row_number'] = [
      '#group' => 'style_options][advanced_settings',
      '#title' => $this
        ->t('Show views result row number in marker'),
      '#type' => 'checkbox',
      '#default_value' => $this->options['marker_row_number'],
    ];
    $form['context_popup_content'] = [
      '#group' => 'style_options][advanced_settings',
      '#type' => 'textarea',
      '#title' => $this
        ->t('Context popup content'),
      '#description' => $this
        ->t('A right click on the map will open a context popup with this content. Tokens supported. Additionally "@lat, @lng" will be replaced dynamically.'),
      '#default_value' => $this->options['context_popup_content'],
    ];

    /*
     * Marker Clusterer
     */
    $form['marker_clusterer_settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Marker Clusterer'),
    ];
    $form['marker_clusterer'] = [
      '#group' => 'style_options][marker_clusterer_settings',
      '#title' => $this
        ->t('Cluster markers'),
      '#type' => 'checkbox',
      '#description' => $this
        ->t('Various <a href=":url">examples</a> are available.', [
        ':url' => 'https://developers.google.com/maps/documentation/javascript/marker-clustering',
      ]),
      '#default_value' => $this->options['marker_clusterer'],
    ];
    $form['marker_clusterer_image_path'] = [
      '#group' => 'style_options][marker_clusterer_settings',
      '#title' => $this
        ->t('Cluster image path'),
      '#type' => 'textfield',
      '#default_value' => $this->options['marker_clusterer_image_path'],
      '#description' => $this
        ->t("Set the marker image path. If omitted, the default image path %url will be used.", [
        '%url' => 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
      ]),
      '#states' => [
        'visible' => [
          ':input[name="style_options[marker_clusterer]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['marker_clusterer_styles'] = [
      '#group' => 'style_options][marker_clusterer_settings',
      '#title' => $this
        ->t('Styles of the Cluster'),
      '#type' => 'textarea',
      '#default_value' => $this->options['marker_clusterer_styles'],
      '#description' => $this
        ->t('Set custom Cluster styles in JSON Format. Custom Styles have to be set for all 5 Cluster Images. See the <a href=":reference">reference</a> for details.', [
        ':reference' => 'https://googlemaps.github.io/js-marker-clusterer/docs/reference.html',
      ]),
      '#states' => [
        'visible' => [
          ':input[name="style_options[marker_clusterer]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];

    /*
     * Google Maps settings
     */
    $form += $this
      ->getGoogleMapsSettingsForm($this->options, 'style_options][');
  }

  /**
   * {@inheritdoc}
   */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    parent::validateOptionsForm($form, $form_state);
    $values = $form_state
      ->getValues()['style_options'];
    $marker_clusterer_styles = $values['marker_clusterer_styles'];
    if (!empty($marker_clusterer_styles)) {
      if (!is_string($marker_clusterer_styles)) {
        $form_state
          ->setErrorByName('style_options][marker_clusterer_styles', $this
          ->t('Please enter a JSON string as style.'));
      }
      $json_result = json_decode($marker_clusterer_styles);
      if ($json_result === NULL) {
        $form_state
          ->setErrorByName('style_options][marker_clusterer_styles', $this
          ->t('Decoding style JSON failed. Error: %error.', [
          '%error' => json_last_error(),
        ]));
      }
      elseif (!is_array($json_result)) {
        $form_state
          ->setErrorByName('style_options][marker_clusterer_styles', $this
          ->t('Decoded style JSON is not an array.'));
      }
    }
    $this
      ->validateGoogleMapsSettingsForm($form, $form_state, 'style_options');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CommonMap::$usesFields protected property Does the style plugin for itself support to add fields to its output. Overrides StylePluginBase::$usesFields
CommonMap::$usesGrouping protected property Does the style plugin support grouping of rows. Overrides StylePluginBase::$usesGrouping
CommonMap::$usesRowClass protected property Does the style plugin support custom css class for the rows. Overrides StylePluginBase::$usesRowClass
CommonMap::$usesRowPlugin protected property Whether or not this style uses a row plugin. Overrides StylePluginBase::$usesRowPlugin
CommonMap::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides StylePluginBase::buildOptionsForm
CommonMap::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides StylePluginBase::defineOptions
CommonMap::evenEmpty public function Should the output of the style plugin be rendered even if it's a empty view. Overrides StylePluginBase::evenEmpty
CommonMap::getMapUpdateOptions protected function Map update option handling.
CommonMap::render public function Render the display in this style. Overrides StylePluginBase::render
CommonMap::validateOptionsForm public function Validate the options form. Overrides StylePluginBase::validateOptionsForm
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
GoogleMapsDisplayTrait::$GOOGLEMAPSAPIURL public static property Google maps url with default parameters.
GoogleMapsDisplayTrait::$HYBRID public static property Google map style - Hybrid.
GoogleMapsDisplayTrait::$MAXZOOMLEVEL public static property Google map max zoom level.
GoogleMapsDisplayTrait::$MINZOOMLEVEL public static property Google map min zoom level.
GoogleMapsDisplayTrait::$ROADMAP public static property Google map style - Roadmap.
GoogleMapsDisplayTrait::$SATELLITE public static property Google map style - Satellite.
GoogleMapsDisplayTrait::$TERRAIN public static property Google map style - Terrain.
GoogleMapsDisplayTrait::getGoogleMapDefaultSettings public static function Provide a populated settings array.
GoogleMapsDisplayTrait::getGoogleMapsApiParameters public function Return all module and custom defined parameters.
GoogleMapsDisplayTrait::getGoogleMapsApiUrl public function Return the fully build URL to load Google Maps API.
GoogleMapsDisplayTrait::getGoogleMapsSettings public function Provide settings ready to handover to JS to feed to Google Maps.
GoogleMapsDisplayTrait::getGoogleMapsSettingsForm public function Provide a generic map settings form array.
GoogleMapsDisplayTrait::getGoogleMapsSettingsSummary public function Provide a summary array to use in field formatters.
GoogleMapsDisplayTrait::getMapTypes private function An array of all available map types.
GoogleMapsDisplayTrait::validateGoogleMapsSettingsForm public function Validate the form elements defined above.
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::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 62
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.
PluginBase::__construct public function Constructs a PluginBase object. Overrides PluginBase::__construct
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::$usesOptions protected property Denotes whether the plugin has an additional options form. Overrides PluginBase::$usesOptions
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::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.