You are here

class LeafletDemoForm in Leaflet More Maps 8

Same name and namespace in other branches
  1. 2.1.x leaflet_demo/src/Form/LeafletDemoForm.php \Drupal\leaflet_demo\Form\LeafletDemoForm

Class LeafletDemoForm.

Hierarchy

Expanded class hierarchy of LeafletDemoForm

1 string reference to 'LeafletDemoForm'
leaflet_demo.routing.yml in leaflet_demo/leaflet_demo.routing.yml
leaflet_demo/leaflet_demo.routing.yml

File

leaflet_demo/src/Form/LeafletDemoForm.php, line 14

Namespace

Drupal\leaflet_demo\Form
View source
class LeafletDemoForm extends FormBase {

  // Old Royal Observatory, Greenwich, near London, England.
  // It's right on the zero-meridian!
  const LEAFLET_DEMO_DEFAULT_LAT = 51.47774;
  const LEAFLET_DEMO_DEFAULT_LNG = -0.001164;
  const LEAFLET_DEMO_DEFAULT_ZOOM = 11;

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

  /**
   * The Drupal Render Service.
   *
   * @var \Drupal\Core\Render\Renderer
   */
  protected $renderer;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'leaflet_demo_page';
  }

  /**
   * LeafletDemoPage constructor.
   *
   * @param \Drupal\leaflet\LeafletService $leaflet_service
   *   The Leaflet Map service.
   * @param \Drupal\Core\Render\Renderer $renderer
   *   The drupal render service.
   */
  public function __construct(LeafletService $leaflet_service, Renderer $renderer) {
    $this->leafletService = $leaflet_service;
    $this->renderer = $renderer;
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state
      ->setRebuild(TRUE);
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    global $base_url;
    $values = $form_state
      ->getUserInput();
    if (empty($values['latitude'])) {
      $latitude = LeafletDemoForm::LEAFLET_DEMO_DEFAULT_LAT;
      $longitude = LeafletDemoForm::LEAFLET_DEMO_DEFAULT_LNG;
    }
    else {
      $latitude = $values['latitude'];
      $longitude = $values['longitude'];
    }
    $zoom = isset($values['zoom']) ? $values['zoom'] : LeafletDemoForm::LEAFLET_DEMO_DEFAULT_ZOOM;
    $form['demo_map_parameters'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Map parameters'),
      '#description' => $this
        ->t('All maps below are centered on the same latitude, longitude and have the same initial zoom level.<br/>You may pan/drag and zoom each map individually.'),
    ];
    $form['demo_map_parameters']['latitude'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Latitude'),
      '#description' => $this
        ->t('-90 .. 90 degrees'),
      '#size' => 12,
      '#default_value' => $latitude,
    ];
    $form['demo_map_parameters']['longitude'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Longitude'),
      '#description' => $this
        ->t('-180 .. 180 degrees'),
      '#size' => 12,
      '#default_value' => $longitude,
    ];
    $form['demo_map_parameters']['zoom'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Zoom'),
      '#field_suffix' => $this
        ->t('(0..18)'),
      '#description' => $this
        ->t('Some zoom levels may not be available in some maps.'),
      '#size' => 2,
      '#default_value' => $zoom,
    ];
    $form['demo_map_parameters']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit map parameters'),
    ];
    $form['#attached']['library'][] = 'leaflet_demo/leaflet_demo_form';
    $form['demo_maps'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('All available maps'),
      '#description' => '<em>' . $this
        ->t('If some maps do not display, this may be due to a missing or invalid map provider API key.') . '<br/>' . $this
        ->t('You can enter API keys <a href="@config_page">here</a>.', [
        '@config_page' => $base_url . '/admin/config/system/leaflet-more-maps/',
      ]) . '</em>',
    ];
    $form['demo_maps'] = array_merge($form['demo_maps'], $this
      ->outputDemoMaps($latitude, $longitude, $zoom));
    return $form;
  }

  /**
   * Outputs the HTML for available Leaflet maps, centered on supplied coords.
   *
   * @param float $latitude
   *   The latitude, -90..90 degrees.
   * @param float $longitude
   *   The longitude, -180..180 degrees.
   * @param int $zoom
   *   The zoom level, typically 0..18.
   *
   * @return array
   *   An array of maps as renderable arrays.
   */
  protected function outputDemoMaps($latitude = LeafletDemoForm::LEAFLET_DEMO_DEFAULT_LAT, $longitude = LeafletDemoForm::LEAFLET_DEMO_DEFAULT_LNG, $zoom = LeafletDemoForm::LEAFLET_DEMO_DEFAULT_ZOOM) {
    if (!is_numeric($latitude) || !is_numeric($longitude) || !is_numeric($zoom)) {
      return [];
    }
    $center = [
      'lat' => $latitude,
      'lon' => $longitude,
    ];
    $feature = [
      'type' => 'point',
      'lat' => $latitude,
      'lon' => $longitude,
      'popup' => $this
        ->t('Location as entered above'),
    ];
    $demo_maps = [];
    $map_info = leaflet_map_get_info();
    foreach ($map_info as $map_id => $map) {
      $map['id'] = $feature['leaflet_id'] = str_replace(' ', '-', $map_id);
      $map['settings']['map_position'] = $center;
      $map['settings']['zoom'] = $zoom;
      $render_object = $this->leafletService
        ->leafletRenderMap($map, [
        $feature,
      ], '350px');
      $demo_maps[$map_id] = [
        '#type' => 'item',
        '#title' => $map_info[$map_id]['label'],
        '#markup' => $this->renderer
          ->render($render_object),
        '#attributes' => [
          'class' => [
            'leaflet-gallery-map',
          ],
        ],
      ];
    }
    return $demo_maps;
  }

}

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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LeafletDemoForm::$leafletService protected property The Leaflet Service.
LeafletDemoForm::$renderer protected property The Drupal Render Service.
LeafletDemoForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
LeafletDemoForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
LeafletDemoForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
LeafletDemoForm::LEAFLET_DEMO_DEFAULT_LAT constant
LeafletDemoForm::LEAFLET_DEMO_DEFAULT_LNG constant
LeafletDemoForm::LEAFLET_DEMO_DEFAULT_ZOOM constant
LeafletDemoForm::outputDemoMaps protected function Outputs the HTML for available Leaflet maps, centered on supplied coords.
LeafletDemoForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
LeafletDemoForm::__construct public function LeafletDemoPage constructor.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.