You are here

function device_geolocation_page_attachments in Smart IP 8.3

Same name and namespace in other branches
  1. 8.4 modules/device_geolocation/device_geolocation.module \device_geolocation_page_attachments()

Implements hook_page_attachments().

File

modules/device_geolocation/device_geolocation.module, line 93
Provides visitor's geographical location using client device location source that implements W3C Geolocation API and Google Geocoding service.

Code

function device_geolocation_page_attachments(array &$page) {
  if (!\Drupal\smart_ip\SmartIp::checkAllowedPage()) {

    // This page is not on the list to access user's geolocation
    return;
  }
  $config = \Drupal::config(SmartIpEventSubscriber::configName());
  $useAjaxCheck = $config
    ->get('use_ajax_check');
  if ($useAjaxCheck || DeviceGeolocation::isNeedUpdate()) {

    /** @var \Drupal\smart_ip\SmartIpLocation $location */
    $location = \Drupal::service('smart_ip.smart_ip_location');

    // Send current user's geolocation to javascript.
    $page['#attached']['drupalSettings']['device_geolocation'] = $location
      ->getData(FALSE);
    $debugMode = SmartIp::isUserDebugMode();

    //$debugMode = FALSE;
    $page['#attached']['drupalSettings']['device_geolocation']['debugMode'] = $debugMode;
    if ($useAjaxCheck) {

      // Add javascript app that checks if device geolocation needs refresh via
      // ajax call.
      $page['#attached']['library'][] = 'device_geolocation/drupal.device_geolocation.check';
      $page['#attached']['drupalSettings']['device_geolocation']['askGeolocate'] = FALSE;
    }
    else {
      $page['#attached']['drupalSettings']['device_geolocation']['askGeolocate'] = TRUE;
    }
    $param = '';
    $apiKey = $config
      ->get('google_map_api_key');
    $languageRegion = $config
      ->get('google_map_region');
    $languageVal = $config
      ->get('google_map_language');
    if ($apiKey) {
      $param .= "key={$apiKey}";
    }
    if ($languageVal) {
      $param .= "&language={$languageVal}";
    }
    if ($languageRegion) {
      $param .= "&region={$languageRegion}";
    }
    $page['#attached']['html_head'][] = [
      [
        '#type' => 'html_tag',
        '#tag' => 'script',
        '#attributes' => [
          'src' => "//maps.googleapis.com/maps/api/js?{$param}",
          'async' => TRUE,
          'defer' => TRUE,
        ],
      ],
      'device_geolocation_google_map_lib',
    ];
    $page['#attached']['library'][] = 'device_geolocation/drupal.device_geolocation.core';
  }
}