You are here

class OpenlayersService in Openlayers 8.4

Provides an OpenlayersService class.

Hierarchy

Expanded class hierarchy of OpenlayersService

6 files declare their use of OpenlayersService
OpenlayersGeofieldFormatter.php in modules/openlayers_geofield/src/Plugin/Field/FieldFormatter/OpenlayersGeofieldFormatter.php
OpenlayersGeofieldWidget.php in modules/openlayers_geofield/src/Plugin/Field/FieldWidget/OpenlayersGeofieldWidget.php
OpenlayersGeolocationFormatter.php in modules/openlayers_geolocation/src/Plugin/Field/FieldFormatter/OpenlayersGeolocationFormatter.php
OpenlayersGeolocationWidget.php in modules/openlayers_geolocation/src/Plugin/Field/FieldWidget/OpenlayersGeolocationWidget.php
OpenlayersMap.php in src/Plugin/views/style/OpenlayersMap.php
Definition of Drupal\openlayers\Plugin\views\style\OpenlayersMap.

... See full list

1 string reference to 'OpenlayersService'
openlayers.services.yml in ./openlayers.services.yml
openlayers.services.yml
1 service uses OpenlayersService
openlayers.service in ./openlayers.services.yml
Drupal\openlayers\OpenlayersService

File

src/OpenlayersService.php, line 17

Namespace

Drupal\openlayers
View source
class OpenlayersService {

  /**
   * Current user service.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The geoPhpWrapper service.
   *
   * @var \Drupal\openlayers\GeoPHP\GeoPHPInterface
   */
  protected $geoPhpWrapper;

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

  /**
   * The Link generator Service.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  protected $link;

  /**
   * LeafletService constructor.
   *
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   Current user service.
   * @param \Drupal\openlayers\GeoPHP\GeoPHPInterface $geophp_wrapper
   *   The geoPhpWrapper.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   The Link Generator service.
   */
  public function __construct(AccountInterface $current_user, GeoPHPInterface $geophp_wrapper, ModuleHandlerInterface $module_handler, LinkGeneratorInterface $link_generator) {
    $this->currentUser = $current_user;
    $this->geoPhpWrapper = $geophp_wrapper;
    $this->moduleHandler = $module_handler;
    $this->link = $link_generator;
  }

  /**
   * Load all Leaflet required client files and return markup for a map.
   *
   * @param array $map
   *   The map settings array.
   * @param array $features
   *   The features array.
   * @param string $height
   *   The height value string.
   *
   * @return array
   *   The leaflet_map render array.
   */
  public function openlayersRenderMap(array $settings, $height = '300px', $cache_tags = NULL) {
    $map = $settings['map'];
    $map_id = isset($map['id']) ? $map['id'] : Html::getUniqueId('openlayers_map');
    $attached_libraries = [
      'openlayers/openlayers-drupal',
    ];
    $js_settings[$map_id] = [
      'mapid' => $map_id,
      'map' => $map,
      'features' => array_values($settings['features']),
      'zoom' => isset($settings['settings']['zoom']) ? $settings['settings']['zoom'] : 10,
      'widget' => isset($settings['widget']) ? $settings['widget'] : [],
    ];
    return [
      '#theme' => 'openlayers_map',
      '#map_id' => $map_id,
      '#height' => $height,
      '#map' => $map,
      '#attached' => [
        'library' => $attached_libraries,
        'drupalSettings' => [
          'openlayers' => $js_settings,
        ],
      ],
      '#cache' => [
        'tags' => $cache_tags,
      ],
    ];
  }

  /**
   * Get all available Leaflet map definitions.
   *
   * @param string $map
   *   The specific map definition string.
   *
   * @return array
   *   The leaflet maps definition array.
   */
  public function XXopenlayersMapGetInfo($map = NULL) {
    static $drupal_static_fast;
    if (!isset($drupal_static_fast)) {
      $drupal_static_fast['openlayers_map_info'] =& drupal_static(__FUNCTION__);
    }
    $map_info =& $drupal_static_fast['openlayers_map_info'];
    if (empty($map_info)) {
      if ($cached = \Drupal::cache()
        ->get('openlayers_map_info')) {
        $map_info = $cached->data;
      }
      else {
        $map_info = $this->moduleHandler
          ->invokeAll('openlayers_map_info');

        // Let other modules alter the map info.
        $this->moduleHandler
          ->alter('openlayers_map_info', $map_info);
        \Drupal::cache()
          ->set('openlayers_map_info', $map_info);
      }
    }
    if (empty($map)) {
      return $map_info;
    }
    else {
      return isset($map_info[$map]) ? $map_info[$map] : [];
    }
  }

  /**
   * Convert a geofield into an array of map points.
   *
   * The map points can then be fed into $this->leafletRenderMap().
   *
   * @param mixed $items
   *   A single value or array of geo values, each as a string in any of the
   *   supported formats or as an array of $item elements, each with a
   *   $item['wkt'] field.
   *
   * @return array
   *   The return array.
   */
  public function openlayersProcessGeofield($items = []) {
    if (!is_array($items)) {
      $items = [
        $items,
      ];
    }
    $data = [];
    foreach ($items as $item) {

      // Auto-detect and parse the format (e.g. WKT, JSON etc).

      /* @var \GeometryCollection $geom */
      if (!($geom = $this->geoPhpWrapper
        ->load(isset($item['wkt']) ? $item['wkt'] : $item))) {
        continue;
      }
      $data[] = $geom;
    }
    return $data;
  }

  /**
   * Process the Geometry Collection.
   *
   * @param \Geometry $geom
   *   The Geometry Collection.
   *
   * @return array
   *   The return array.
   */
  private function openlayersProcessGeometry(\Geometry $geom) {
    $datum = [
      'type' => strtolower($geom
        ->geometryType()),
    ];
    switch ($datum['type']) {
      case 'point':
        $datum = [
          'type' => 'point',
          'lat' => $geom
            ->getY(),
          'lon' => $geom
            ->getX(),
        ];
        break;
      case 'linestring':

        /* @var \GeometryCollection $geom */
        $components = $geom
          ->getComponents();

        /* @var \Geometry $component */
        foreach ($components as $component) {
          $datum['points'][] = [
            'lat' => $component
              ->getY(),
            'lon' => $component
              ->getX(),
          ];
        }
        break;
      case 'polygon':

        /* @var \GeometryCollection $geom */
        $tmp = $geom
          ->getComponents();

        /* @var \GeometryCollection $geom */
        $geom = $tmp[0];
        $components = $geom
          ->getComponents();

        /* @var \Geometry $component */
        foreach ($components as $component) {
          $datum['points'][] = [
            'lat' => $component
              ->getY(),
            'lon' => $component
              ->getX(),
          ];
        }
        break;
      case 'multipolyline':
      case 'multilinestring':
        if ($datum['type'] == 'multilinestring') {
          $datum['type'] = 'multipolyline';
          $datum['multipolyline'] = TRUE;
        }

        /* @var \GeometryCollection $geom */
        $components = $geom
          ->getComponents();

        /* @var \GeometryCollection $component */
        foreach ($components as $key => $component) {
          $subcomponents = $component
            ->getComponents();

          /* @var \Geometry $subcomponent */
          foreach ($subcomponents as $subcomponent) {
            $datum['component'][$key]['points'][] = [
              'lat' => $subcomponent
                ->getY(),
              'lon' => $subcomponent
                ->getX(),
            ];
          }
          unset($subcomponent);
        }
        break;
      case 'multipolygon':
        $components = [];

        /* @var \GeometryCollection $geom */
        $tmp = $geom
          ->getComponents();

        /* @var \GeometryCollection $polygon */
        foreach ($tmp as $delta => $polygon) {
          $polygon_component = $polygon
            ->getComponents();
          foreach ($polygon_component as $k => $linestring) {
            $components[] = $linestring;
          }
        }
        foreach ($components as $key => $component) {
          $subcomponents = $component
            ->getComponents();

          /* @var \Geometry $subcomponent */
          foreach ($subcomponents as $subcomponent) {
            $datum['component'][$key]['points'][] = [
              'lat' => $subcomponent
                ->getY(),
              'lon' => $subcomponent
                ->getX(),
            ];
          }
        }
        break;
      case 'geometrycollection':
      case 'multipoint':

        /* @var \GeometryCollection $geom */
        $components = $geom
          ->getComponents();
        foreach ($components as $key => $component) {
          $datum['component'][$key] = $this
            ->openlayersProcessGeometry($component);
        }
        break;
    }
    return $datum;
  }

  /**
   * Pre Process the MapSettings.
   *
   * Performs some preprocess on the maps settings before sending to js.
   *
   * @param array $map_settings
   *   The map settings.
   */
  public function preProcessMapSettings(array &$map_settings) {

    // Generate correct Absolute iconUrl & shadowUrl, if not external.
    if (!empty($map_settings['icon']['iconUrl'])) {
      $map_settings['icon']['iconUrl'] = $this
        ->pathToAbsolute($map_settings['icon']['iconUrl']);
    }
    if (!empty($map_settings['icon']['shadowUrl'])) {
      $map_settings['icon']['shadowUrl'] = $this
        ->pathToAbsolute($map_settings['icon']['shadowUrl']);
    }
  }
  public function getMapConfig($map_id) {
    $map_config = \Drupal::config('openlayers.openlayers_map.' . $map_id);
    $map_settings = [];

    //  get Layers settings
    if ($map_config
      ->get('layers') != NULL) {
      $layers = [];
      foreach ($map_config
        ->get('layers') as $layer_id => $layer) {
        if ($layer != FALSE) {
          $layers[$layer_id] = $this
            ->getLayerConfig($layer_id);
        }
      }
      $map_settings['layers'] = $layers;
    }

    //  get Interactions settings
    if ($map_config
      ->get('interactions') != NULL) {
      $interactions = [];
      foreach ($map_config
        ->get('interactions') as $key => $interaction) {
        if ($interaction != FALSE) {
          $interactions[$key] = $interaction;
        }
      }
      $map_settings['interactions'] = $interactions;
    }

    //  get Controls settings
    if ($map_config
      ->get('controls') != NULL) {
      $controls = [];
      foreach ($map_config
        ->get('controls') as $key => $control) {
        if ($control != FALSE) {
          $controls[$key] = $control;
        }
      }
      $map_settings['controls'] = $controls;
    }
    return $map_settings;
  }
  public function getLayerConfig($layer_id) {
    $layer_config = \Drupal::config('openlayers.openlayers_layer.' . $layer_id);
    $layer_settings = [
      'type' => $layer_config
        ->get('layer_type'),
      'source' => $this
        ->getSourceConfig($layer_config
        ->get('source')),
    ];
    return $layer_settings;
  }
  public function getSourceConfig($source_id) {
    $source_config = \Drupal::config('openlayers.openlayers_source.' . $source_id);
    $source_settings = [
      'type' => $source_config
        ->get('source_type'),
    ];
    return $source_settings;
  }

  ///////////////////////////////////////////////

  /**
   * Generate an Absolute Url from a string Path.
   *
   * @param string $path
   *   The path string to generate.
   *
   * @return string
   *   The absolute $path
   */
  public function pathToAbsolute($path) {
    if (!UrlHelper::isExternal($path)) {
      $path = Url::fromUri('base:', [
        'absolute' => TRUE,
      ])
        ->toString() . $path;
    }
    return $path;
  }

  /**
   * Check if an array has all values empty.
   *
   * @param array $array
   *   The array to check.
   *
   * @return bool
   *   The bool result.
   */
  public function multipleEmpty(array $array) {
    foreach ($array as $value) {
      if (empty($value)) {
        continue;
      }
      else {
        return FALSE;
      }
    }
    return TRUE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
OpenlayersService::$currentUser protected property Current user service.
OpenlayersService::$geoPhpWrapper protected property The geoPhpWrapper service.
OpenlayersService::$link protected property The Link generator Service.
OpenlayersService::$moduleHandler protected property The module handler.
OpenlayersService::getLayerConfig public function
OpenlayersService::getMapConfig public function
OpenlayersService::getSourceConfig public function
OpenlayersService::multipleEmpty public function Check if an array has all values empty.
OpenlayersService::openlayersProcessGeofield public function Convert a geofield into an array of map points.
OpenlayersService::openlayersProcessGeometry private function Process the Geometry Collection.
OpenlayersService::openlayersRenderMap public function Load all Leaflet required client files and return markup for a map.
OpenlayersService::pathToAbsolute public function Generate an Absolute Url from a string Path.
OpenlayersService::preProcessMapSettings public function Pre Process the MapSettings.
OpenlayersService::XXopenlayersMapGetInfo public function Get all available Leaflet map definitions.
OpenlayersService::__construct public function LeafletService constructor.