You are here

class LeafletGeojson in Leaflet GeoJSON 8

Provides a 'Leaflet Geojson' Block.

Plugin annotation


@Block(
  id = "leaflet_geojson",
  admin_label = @Translation("Leaflet Geojson Map Block"),
  category = @Translation("Mapping"),
)

Hierarchy

Expanded class hierarchy of LeafletGeojson

File

src/Plugin/Block/LeafletGeojson.php, line 21

Namespace

Drupal\leaflet_geojson\Plugin\Block
View source
class LeafletGeojson extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The Leaflet service.
   *
   * @var Drupal\Leaflet\LeafletService
   */
  protected $leafletService;

  /**
   * Constructs a LeafletGeojson object.
   */
  public function __construct($configuration, $plugin_id, $plugin_definition, ModuleHandlerInterface $module_handler, LeafletService $leaflet_service) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->moduleHandler = $module_handler;
    $this->leafletService = $leaflet_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('module_handler'), $container
      ->get('leaflet.service'));
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = $this
      ->leafletGeojsonMapPaneRenderLayeredMap();

    /* Adding geojson specificities*/
    $build['#theme'] = 'leafletgeojson_map';
    $geojsonBuildArray = [
      '#attached' => [
        'library' => $this
          ->leafletGeojsonMapPaneRenderJavascriptLibrary(),
        'drupalSettings' => [
          'leafletBBox' => $this
            ->leafletGeojsonMapPaneRenderJavascriptSettings(),
        ],
      ],
    ];
    $build = array_merge_recursive($build, $geojsonBuildArray);
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $conf = $this->configuration;

    // Build base layer selector.
    $base_options = [];
    foreach (leaflet_map_get_info() as $key => $map) {
      $base_options[$key] = $this
        ->t('@label', [
        '@label' => $map['label'],
      ]);
    }

    // The default selection is the first one, or the previously selected one.
    $default_base = key($base_options);
    if (isset($conf['map_settings']['base'])) {
      $default_base = $conf['map_settings']['base'];
    }
    $form['map_settings']['base'] = [
      '#title' => $this
        ->t('Leaflet base layer'),
      '#type' => 'select',
      '#options' => $base_options,
      '#default_value' => $default_base,
      '#required' => TRUE,
      '#description' => $this
        ->t('Select the Leaflet base layer (map style) that will display the data.'),
    ];

    // Provide some UI help for setting up multi-layer maps.
    $data_layers_description = $this
      ->t('Choose one or more GeoJSON sources that will provide the map data.') . ' ';
    $data_layers_description .= $this
      ->t('If more than one source  is selected, a layer control will appear on the map.') . ' ';
    $data_layers_description .= $this
      ->t('Views GeoJSON page displays are automatically exposed here.');

    // Build the data layers selector.
    $form['map_settings']['info'] = [
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#title' => 'Views GeoJSON Data Layers',
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#description' => $data_layers_description,
    ];

    // Grab the available layers.
    $sources = leaflet_geojson_source_get_info(NULL, TRUE);
    $source_options = [];
    foreach ($sources as $id => $source) {
      $source_options[$id] = $source['title'];
    }

    // Figure out if we have any data layers yet, and set the layer count.
    if (empty($form_state
      ->get('layer_count'))) {

      // During creation, we wont have any data yet, so only one layer.
      if (!isset($conf['map_settings']['info']['data'])) {
        $form_state
          ->set('layer_count', 1);
      }
      else {

        // During edit, we'll have one or more layers, so count.
        $form_state
          ->set('layer_count', count($conf['map_settings']['info']['data']));
      }
    }

    // Build the number of layer selections indicated by layer_count.
    for ($layer_index = 1; $layer_index <= $form_state
      ->get('layer_count'); $layer_index++) {
      $default_layer_source = key($source_options);
      if (isset($conf['map_settings']['info']['data']['leaflet_' . $layer_index])) {
        $default_layer_source = $conf['map_settings']['info']['data']['leaflet_' . $layer_index];
      }
      $form['map_settings']['info']['data']['leaflet_' . $layer_index] = [
        '#type' => 'select',
        '#title' => $this
          ->t('GeoJSON layer source'),
        '#options' => $source_options,
        '#default_value' => $default_layer_source,
        '#required' => $layer_index == 1,
      ];
    }

    // Provide an "Add another layer" button.
    $form['map_settings']['info']['add_layer'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add another layer'),
      '#submit' => [
        'leaflet_geojson_map_pane_add_layer',
      ],
    ];

    // Provide a "Remove" button for latest selected layer.
    if ($form_state
      ->get('layer_count') > 1) {
      $form['map_settings']['info']['remove_layer'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Remove last layer'),
        '#submit' => [
          'leaflet_geojson_map_pane_remove_last_layer',
        ],
      ];
    }

    // Leaflet wants a height in the call to the render function.
    $default_height = isset($conf['map_settings']['height']) ? $conf['map_settings']['height'] : 400;
    $form['map_settings']['height'] = [
      '#title' => $this
        ->t('Map height'),
      '#type' => 'textfield',
      '#size' => 4,
      '#default_value' => $default_height,
      '#required' => FALSE,
      '#description' => $this
        ->t("Set the map height"),
    ];

    // Added to have 100% in height.
    $form['map_settings']['height_unit'] = [
      '#title' => $this
        ->t('Map height unit'),
      '#type' => 'select',
      '#options' => [
        'px' => $this
          ->t('px'),
        '%' => $this
          ->t('%'),
      ],
      '#default_value' => isset($conf['map_settings']['height_unit']) ? $conf['map_settings']['height_unit'] : 'px',
      '#description' => $this
        ->t('Wether height is absolute (pixels) or relative (percent).'),
    ];

    // Optionally override natural center and zoom.
    $default_override_zoom_center = isset($conf['map_settings']['override_zoom_center']) && $conf['map_settings']['override_zoom_center'];
    $form['map_settings']['override_zoom_center'] = [
      '#type' => 'checkbox',
      '#title' => 'Override natural center and zoom placement',
      '#default_value' => $default_override_zoom_center,
      '#description' => $this
        ->t("Map will auto zoom and center based on the data. Check this box to customize the zooom and center"),
    ];
    $form['map_settings']['custom_zoom_center'] = [
      '#type' => 'fieldset',
      '#title' => 'Zoom and Center',
      '#tree' => TRUE,
      '#states' => [
        'visible' => [
          ':input[name="override_zoom_center"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $default_zoom = isset($conf['map_settings']['custom_zoom_center']['zoom']) ? $conf['map_settings']['custom_zoom_center']['zoom'] : 1;
    $form['map_settings']['custom_zoom_center']['zoom'] = [
      '#title' => $this
        ->t('Zoom'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $default_zoom,
      '#required' => FALSE,
    ];
    $form['map_settings']['custom_zoom_center']['center'] = [
      '#type' => 'fieldset',
      '#title' => 'Map center',
      '#tree' => TRUE,
      '#description' => $this
        ->t("Provide a default map center especially when using the bounding box strategy."),
    ];
    $default_center = isset($conf['map_settings']['custom_zoom_center']['center']) ? $conf['map_settings']['custom_zoom_center']['center'] : [
      'lon' => 0,
      'lat' => 0,
    ];
    $form['map_settings']['custom_zoom_center']['center']['lon'] = [
      '#title' => $this
        ->t('Center longitude'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $default_center['lon'],
      '#required' => FALSE,
    ];
    $form['map_settings']['custom_zoom_center']['center']['lat'] = [
      '#title' => $this
        ->t('Center latitude'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $default_center['lat'],
      '#required' => FALSE,
    ];
    return $form;
  }

  /**
   * Submit handler just puts non-empty values into configuration.
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    foreach ($form['settings']['map_settings'] as $key => $content) {

      // The override_zoom_center property could be empty, we want to track it.
      if (!empty($form_state
        ->getValue([
        'map_settings',
        $key,
      ])) || $key == 'override_zoom_center') {
        $this->configuration['map_settings'][$key] = $form_state
          ->getValue([
          'map_settings',
          $key,
        ]);
      }
    }
  }

  /**
   * Helper function to generate the javascript settings.
   */
  private function leafletGeojsonMapPaneRenderJavascriptLibrary() {

    // Attaching Ajax in case we have node description loaded by ajax.
    $libraries = [
      'leaflet_geojson/leaflet_geojson_bbox',
      'core/drupal.ajax',
    ];

    // Allow other modules to alter the map data.
    $this->moduleHandler
      ->alter('leaflet_geojson_map_pane_render_javascript_library', $libraries);
    return $libraries;
  }

  /**
   * Helper function to generate the javascript settings.
   */
  private function leafletGeojsonMapPaneRenderJavascriptSettings() {
    $conf = $this->configuration;

    // Gather information about the leaflet base and data layers.
    $data_layers_info = [];
    foreach ($conf['map_settings']['info']['data'] as $layer_idx => $layer_machine_name) {
      $data_layers_info[$layer_idx] = leaflet_geojson_source_get_info($layer_machine_name);
    }
    return $data_layers_info;
  }

  /**
   * Helper function to generate the map markup based on the pane config.
   */
  private function leafletGeojsonMapPaneRenderLayeredMap() {
    $conf = $this->configuration;

    // Gather information about the leaflet base and data layers.
    $map_base_info = leaflet_map_get_info($conf['map_settings']['base']);
    $data_layers_info = [];
    foreach ($conf['map_settings']['info']['data'] as $layer_idx => $layer_machine_name) {
      $data_layers_info[$layer_idx] = leaflet_geojson_source_get_info($layer_machine_name);
    }

    // We are not currently supporting mixed bounding, i.e. if any one layer
    // is not bounded, then all layers will be fetched non-bounded. This will
    // have serious performance impact at large scale.
    $all_bounded = TRUE;
    foreach ($data_layers_info as $layer_idx => $layer_info) {
      if (!isset($layer_info['bbox'])) {
        $all_bounded = FALSE;
        break;
      }
    }
    $feature_layers = [];
    if ($all_bounded) {

      // Ensure the map center is non-empty for bbox.
      if (empty($map_base_info['center'])) {
        $map_base_info['center'] = [
          'lon' => 0,
          'lat' => 0,
        ];
      }
    }
    else {

      /* @TODO: non-bounded data fetch */
    }

    // Apply any overrides of natural center and zoom.
    if (!empty($conf['map_settings']['override_zoom_center'])) {
      if (!empty($conf['map_settings']['custom_zoom_center']['zoom'])) {
        $map_base_info['settings']['zoom'] = $conf['map_settings']['custom_zoom_center']['zoom'];
        $map_base_info['settings']['map_position_force'] = TRUE;
      }
      if (!empty($conf['map_settings']['custom_zoom_center']['center']['lat']) && !empty($conf['map_settings']['custom_zoom_center']['center']['lon'])) {
        $map_base_info['settings']['center'] = [
          'lat' => $conf['map_settings']['custom_zoom_center']['center']['lat'],
          'lon' => $conf['map_settings']['custom_zoom_center']['center']['lon'],
        ];
      }
    }

    // Allow other modules to alter the map data.
    $this->moduleHandler
      ->alter('leaflet_geojson_map_pane', $map_base_info, $feature_layers);
    $map_build = $this->leafletService
      ->leafletRenderMap($map_base_info, $feature_layers, $conf['map_settings']['height'] . $conf['map_settings']['height_unit']);
    return $map_build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. 2
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::defaultConfiguration public function 19
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 9
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 4
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
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
LeafletGeojson::$leafletService protected property The Leaflet service.
LeafletGeojson::$moduleHandler protected property The module handler service.
LeafletGeojson::blockForm public function Overrides BlockPluginTrait::blockForm
LeafletGeojson::blockSubmit public function Submit handler just puts non-empty values into configuration. Overrides BlockPluginTrait::blockSubmit
LeafletGeojson::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build
LeafletGeojson::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
LeafletGeojson::leafletGeojsonMapPaneRenderJavascriptLibrary private function Helper function to generate the javascript settings.
LeafletGeojson::leafletGeojsonMapPaneRenderJavascriptSettings private function Helper function to generate the javascript settings.
LeafletGeojson::leafletGeojsonMapPaneRenderLayeredMap private function Helper function to generate the map markup based on the pane config.
LeafletGeojson::__construct public function Constructs a LeafletGeojson object. Overrides BlockPluginTrait::__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::$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.
PluginWithFormsTrait::getFormClass public function
PluginWithFormsTrait::hasFormClass public function
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.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2