You are here

addressfield_staticmap.module in Address Field Static Map 7

Main file for the addressfield static map module.

File

addressfield_staticmap.module
View source
<?php

/**
 * @file
 * Main file for the addressfield static map module.
 */
define('DEFAULT_MAP_SIZE', '400x400');

/**
 * Implements hook_permission().
 */
function addressfield_staticmap_permission() {
  return array(
    'administer addressfield staticmap' => array(
      'title' => t('Administer Address Field Static Map'),
      'description' => t('Change Google Static Map and other settings for this block.'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function addressfield_staticmap_menu() {
  $items['admin/config/system/addressfield_staticmap'] = array(
    'title' => 'Address Field Static Map Block',
    'description' => 'Configure settings for the address field static map block.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'addressfield_staticmap_admin_form',
    ),
    'file' => 'addressfield_staticmap.admin.inc',
    'access arguments' => array(
      'administer addressfield staticmap',
    ),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implements hook_block_info().
 */
function addressfield_staticmap_block_info() {
  $blocks['addressfield_staticmap'] = array(
    'info' => t('Address Field Static Map'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  $blocks['addressfield_staticmap_alt'] = array(
    'info' => t('Address Field Static Map (alternate)'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function addressfield_staticmap_block_view($delta = '') {
  $block = array();
  $deltas = array(
    'addressfield_staticmap',
    'addressfield_staticmap_alt',
  );
  if (!in_array($delta, $deltas)) {
    return $block;
  }
  $index = array_search($delta, $deltas);

  // Check if the address field name is configured.
  $field_names = variable_get('addressfield_staticmap_field_names', '');
  if (empty($field_names) || !array_filter($field_names)) {
    return $block;
  }
  $entity = menu_get_object();
  if (empty($entity)) {
    return $block;
  }
  $block['subject'] = t('Address Field Static Map');
  $block['content'] = '';

  // Do this for each of the enabled address fields.
  foreach ($field_names as $field_name) {
    if (empty($entity->base_type)) {
      continue;
    }
    $fields = field_get_items($entity->base_type, $entity, $field_name, $entity->language);
    if (empty($fields)) {
      continue;
    }

    // Fetch configuration variables.
    $api = variable_get('addressfield_staticmap_api_' . $index, 'google_maps');

    // Configure base settings.
    $settings = array(
      'zoom' => variable_get('addressfield_staticmap_gmap_zoom_' . $index, 14),
      'size' => variable_get('addressfield_staticmap_gmap_size_' . $index, ''),
      'scroll_lock' => variable_get('addressfield_staticmap_scroll_lock_' . $index, FALSE),
      'maptype' => variable_get('addressfield_staticmap_gmap_type_' . $index, 'roadmap'),
      'scale' => variable_get('addressfield_staticmap_scale_' . $index, 1),
      'index' => $index,
    );
    foreach ($fields as $id => $data) {
      $data_cleaned = array_filter($data);

      // If only the country is set, skip this (for some reason the country
      // value becomes mandatory if you limit the list).
      if (isset($data_cleaned['country']) && count($data_cleaned) <= 1) {
        continue;
      }
      $address = addressfield_staticmap_clean_address($data);

      // Display the address if the checkbox is set.
      if (variable_get('addressfield_staticmap_gmap_show_address_' . $index, FALSE)) {
        $settings['text_address'] = _addressfield_staticmap_render_address($data);
      }

      // Display the info window if the checkbox is set.
      $settings['info_window'] = variable_get('addressfield_staticmap_gmap_show_info_window_' . $index, FALSE);

      // Use Google Maps.
      if ($api == 'google_maps') {
        $settings['icon_url'] = variable_get('addressfield_staticmap_gmap_icon_url_' . $index, '');
        $settings['icon_url'] = empty($settings['icon_url']) ? 'color:green' : 'icon:' . $settings['icon_url'];
        $settings['premier'] = variable_get('addressfield_staticmap_premier_' . $index, '');
        $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $index, '');
        $settings['client_id'] = variable_get('addressfield_staticmap_premium_client_id_' . $index, '');
        $settings['crypto_key'] = variable_get('addressfield_staticmap_premium_crypto_key_' . $index, '');
        $block['content'] .= _addressfield_static_map_render_google_maps_image($address, $settings, $entity);
      }
      elseif ($api == 'google_maps_api') {
        $settings['icon_url'] = variable_get('addressfield_staticmap_gmap_icon_url_' . $index, '');
        $settings['icon_url'] = empty($settings['icon_url']) ? 'color:green' : 'icon:' . $settings['icon_url'];
        $settings['premier'] = variable_get('addressfield_staticmap_premier_' . $index, '');
        $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $index, '');
        $settings['client_id'] = variable_get('addressfield_staticmap_premium_client_id_' . $index, '');
        $settings['crypto_key'] = variable_get('addressfield_staticmap_premium_crypto_key_' . $index, '');
        $block['content'] .= _addressfield_static_map_render_google_maps($address, $settings, $entity);
      }
      elseif ($api == 'google_maps_embed') {
        $settings['icon_url'] = variable_get('addressfield_staticmap_gmap_icon_url_' . $index, '');
        $settings['icon_url'] = empty($settings['icon_url']) ? 'color:green' : 'icon:' . $settings['icon_url'];
        $settings['premier'] = variable_get('addressfield_staticmap_premier_' . $index, '');
        $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $index, '');
        $settings['client_id'] = variable_get('addressfield_staticmap_premium_client_id_' . $index, '');
        $settings['crypto_key'] = variable_get('addressfield_staticmap_premium_crypto_key_' . $index, '');
        $block['content'] .= _addressfield_embed_map_render_google_maps($address, $settings, $entity);
      }
      elseif ($api == 'mapquest') {
        $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $index, '');
        $block['content'] .= _addressfield_static_map_render_mapquest_image($address, $settings);
      }
    }
  }
  return $block;
}

/**
 * Implements hook_theme().
 *
 * Provides theming function used when a regular Google Map is rendered with
 * a static image fallback.
 */
function addressfield_staticmap_theme() {
  return array(
    'addressfield_staticmap_google_map' => array(
      'variables' => array(
        'address' => NULL,
        'settings' => NULL,
        'image' => NULL,
        'kml_paths' => NULL,
      ),
      'template' => 'addressfield-staticmap-google-map',
    ),
    'addressfield_staticmap_static_map' => array(
      'variables' => array(
        'address' => NULL,
        'settings' => NULL,
      ),
      'template' => 'addressfield-staticmap-static-map',
    ),
    'addressfield_staticmap_embed_map' => array(
      'variables' => array(
        'address' => NULL,
        'settings' => NULL,
      ),
      'template' => 'addressfield-staticmap-embed-map',
    ),
  );
}

/**
 * Render static Google Map image for a specific address.
 *
 * @param string $address
 *   The address being displayed.
 * @param array $settings
 *   An array of settings related to the map to be displayed.
 * @param object $entity
 *   The entity to which the field is attached.
 *
 * @return string
 *   Rendered Google map.
 */
function _addressfield_static_map_render_google_maps_image($address, array $settings, $entity) {
  global $is_https;
  $url_args = array(
    'external' => TRUE,
    'https' => $is_https,
    'query' => array(
      'center' => $address,
      'zoom' => $settings['zoom'],
      'size' => $settings['size'],
      'scale' => $settings['scale'],
      'maptype' => $settings['maptype'],
      'markers' => implode('|', array(
        url($settings['icon_url'], array(
          'external' => TRUE,
        )),
        $address,
      )),
    ),
  );
  if ($url_args['query']['zoom'] == 'auto') {
    unset($url_args['query']['zoom']);
  }

  // Check for Google Maps API key vs Premium Plan via Client ID & Signature.
  if (isset($settings['premier']) && $settings['premier']) {
    $url_args['query']['client'] = $settings['client_id'];
  }
  else {
    $url_args['query']['key'] = $settings['api_key'];
  }
  $settings['staticmap_url'] = url('//maps.googleapis.com/maps/api/staticmap', $url_args);
  if (!empty($settings['additional'])) {
    $settings['staticmap_url'] .= '&' . $settings['additional'];
  }
  if (isset($settings['premier']) && $settings['premier']) {
    $data = str_replace('//maps.googleapis.com', '', $settings['staticmap_url']);
    $signature = hash_hmac('sha1', $data, base64_decode(strtr($settings['crypto_key'], '-_', '+/')), true);
    $signature = strtr(base64_encode($signature), '+/', '-_');
    $settings['staticmap_url'] .= '&signature=' . $signature;
  }

  // Google Maps link.
  $url = '//maps.google.com/maps';
  $options = array(
    'external' => TRUE,
    'https' => $is_https,
  );
  $index = $settings['index'];
  $target = variable_get('addressfield_staticmap_gmap_link_target_' . $index, '');
  $rel = variable_get('addressfield_staticmap_noopener_' . $index, FALSE) ? "noopener" : "";

  // Add 'Get directions' text link.
  if (variable_get('addressfield_staticmap_directions_link_' . $index)) {
    $link_text = variable_get('addressfield_staticmap_directions_text_' . $index, t('Get directions'));
    $options['query'] = array(
      'daddr' => $address,
    );
    $options['attributes'] = empty($target) ? array(
      'title' => $link_text,
    ) : array(
      'title' => $link_text,
      'target' => $target,
      'rel' => $rel,
    );
    $settings['directions'] = l($link_text, $url, $options);
  }

  // Link to actual Google map.
  if (variable_get('addressfield_staticmap_gmap_link_' . $index, FALSE)) {
    $attributes = array();
    if (!empty($target)) {
      $attributes['target'] = $target;
    }
    if ($target == '_blank' && !empty($rel)) {
      $attributes['rel'] = $rel;
    }
    $settings['target'] = empty($attributes) ? '' : drupal_attributes($attributes);
    $options['query'] = array(
      'q' => $address,
    );
    $settings['link'] = url($url, $options);
  }
  $render = theme('addressfield_staticmap_static_map', array(
    'address' => $address,
    'settings' => $settings,
    'entity' => $entity,
  ));
  return $render;
}

/**
 * Render regular Google Map for a specific address.
 *
 * @param string $address
 *   The address being displayed.
 * @param array $settings
 *   An array of settings related to the map to be displayed.
 * @param object $entity
 *   The entity to which the field is attached.
 *
 * @return string
 *   Rendered Google map.
 */
function _addressfield_static_map_render_google_maps($address, array $settings, $entity) {

  // Check for Google Maps API key vs Premium Plan via Client ID & Signature.
  if (isset($settings['premier']) && $settings['premier']) {
    $url_args['query']['client'] = $settings['client_id'];
  }
  else {
    $url_args['query']['key'] = $settings['api_key'];
  }
  $maps_url = url('//maps.googleapis.com/maps/api/js', $url_args);
  if (isset($settings['premier']) && $settings['premier']) {
    $data = str_replace('//maps.googleapis.com', '', $settings['staticmap_url']);
    $signature = hash_hmac('sha1', $data, base64_decode(strtr($settings['crypto_key'], '-_', '+/')), true);
    $signature = strtr(base64_encode($signature), '+/', '-_');
    $maps_url .= '&signature=' . $signature;
  }
  drupal_add_js($maps_url, array(
    'group' => 'JS_LIBRARY',
    'type' => 'external',
  ));
  drupal_add_css(drupal_get_path('module', 'addressfield_staticmap') . '/addressfield_staticmap.css');
  $image = _addressfield_static_map_render_google_maps_image($address, $settings, $entity);
  $kml_paths = array();

  // Additional processing to attach optional KML file(s).
  $kml_field_names = array_filter(variable_get('addressfield_staticmap_field_kml', array()));
  if (!empty($kml_field_names) && isset($entity)) {
    foreach ($kml_field_names as $kml_field) {
      $kml_field = explode('|', $kml_field);

      // Check to see if the valid field settings are for this bundle.
      if ($entity->type != $kml_field[0]) {
        continue;
      }
      $kml_files = field_get_items('entity', $entity, $kml_field[1], $entity->language);
      if (empty($kml_files)) {
        continue;
      }
      foreach ($kml_files as $kml_file) {
        $kml_paths[] = file_create_url($kml_file['uri']);
      }
    }
  }
  $render = theme('addressfield_staticmap_google_map', array(
    'address' => urldecode($address),
    'settings' => $settings,
    'image' => $image,
    'kml_paths' => $kml_paths,
    'entity' => $entity,
  ));
  return $render;
}

/**
 * Render regular Google Embed Map for a specific address.
 *
 * @param string $address
 *   The address being displayed.
 * @param array $settings
 *   An array of settings related to the map to be displayed.
 * @param object $entity
 *   The entity to which the field is attached.
 *
 * @return string
 *   Rendered Google map.
 */
function _addressfield_embed_map_render_google_maps($address, array $settings, $entity) {
  drupal_add_css(drupal_get_path('module', 'addressfield_staticmap') . '/addressfield_staticmap.css');
  $render = theme('addressfield_staticmap_embed_map', array(
    'address' => urldecode($address),
    'settings' => $settings,
    'entity' => $entity,
  ));
  return $render;
}

/**
 * Render static Mapquest image for a specific address.
 */
function _addressfield_static_map_render_mapquest_image($address, $settings) {
  global $is_https;
  $settings['size'] = str_replace('x', ',', $settings['size']);

  // Codes for map types are not the same, alter them.
  $map_types = array(
    'roadmap' => 'map',
    'satellite' => 'sat',
    'hybrid' => 'hyb',
    'terrain' => 'map',
  );
  $settings['maptype'] = $map_types[$settings['maptype']];
  $staticmap_url = url('http://www.mapquestapi.com/staticmap/v3/getplacemap', array(
    'external' => TRUE,
    'https' => $is_https,
    'query' => array(
      'key' => $settings['api_key'],
      'location' => $address,
      'size' => $settings['size'],
      'type' => $settings['maptype'],
      'zoom' => $settings['zoom'],
      'scale' => $settings['scale'],
      'imagetype' => 'jpeg',
      'showicon' => 'green-1',
    ),
  ));
  return theme_image(array(
    'path' => $staticmap_url,
  ));
}

/**
 * Implements hook_field_formatter_info().
 */
function addressfield_staticmap_field_formatter_info() {
  return array(
    'addressfield_staticmap' => array(
      'label' => t('Address Field Static Map'),
      'field types' => array(
        'addressfield',
        'location',
      ),
      'settings' => array(
        'zoom_level' => 14,
        'map_size' => '',
        'map_style' => 'roadmap',
        'scale' => 1,
        'advanced_settings_index' => 0,
        'scroll_lock' => FALSE,
        'info_window' => 0,
        'text_address' => 0,
        'additional' => '',
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function addressfield_staticmap_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $form = array();
  if ($display['type'] == 'addressfield_staticmap') {
    $form['zoom_level'] = array(
      '#title' => t('Zoom level'),
      '#type' => 'select',
      '#description' => t('The zoom level to use on the map. Must be between 1 and 16 (inclusive) for Mapquest, or any of the options for Google Mmaps.'),
      '#default_value' => $settings['zoom_level'],
      '#options' => array(
        'auto' => t('Auto'),
      ) + drupal_map_assoc(range(0, 21)),
      '#required' => TRUE,
    );
    $form['map_size'] = array(
      '#title' => t('Map size'),
      '#type' => 'textfield',
      '#size' => 10,
      '#default_value' => $settings['map_size'],
      '#element_validate' => array(
        'addressfield_staticmap_mapsize_validate',
      ),
      '#required' => FALSE,
      '#description' => t("Enter a size for the map in pixels (eg '400x400') or leave blank for the default.<br />When using Google's static maps, the size will default to " . DEFAULT_MAP_SIZE . " if left blank.<br />When using non-static maps, a blank value can be used to apply CSS styling."),
    );
    $form['scroll_lock'] = array(
      '#title' => t('Prevent scrolling and zooming the map.'),
      '#type' => 'checkbox',
      '#default_value' => $settings['scroll_lock'],
    );
    $form['additional'] = array(
      '#title' => t('Additional parameters to use in the map URL (eg styling a map).'),
      '#type' => 'textfield',
      '#size' => 60,
      '#maxlength' => 2048,
      '#default_value' => $settings['additional'],
    );
    $form['info_window'] = array(
      '#title' => t('Show the address in an info window'),
      '#type' => 'checkbox',
      '#default_value' => $settings['info_window'],
    );
    $form['text_address'] = array(
      '#title' => t('Show the address in text format'),
      '#type' => 'checkbox',
      '#default_value' => $settings['text_address'],
    );
    $form['map_style'] = array(
      '#type' => 'select',
      '#title' => t('Map type'),
      '#description' => t('The format to use for the rendered map. Hybrid blends, satellite and roadmap.'),
      '#default_value' => $settings['map_style'],
      '#options' => array(
        'roadmap' => t('Roadmap'),
        'satellite' => t('Satellite'),
        'terrain' => t('Terrain'),
        'hybrid' => t('Hybrid'),
      ),
    );
    $form['scale'] = array(
      '#type' => 'select',
      '#title' => t('Scale'),
      '#description' => t('The scale parameter for the image (retina). 4 will only work on Google if you have a premium subscription.'),
      '#default_value' => $settings['scale'],
      '#options' => array(
        1 => t('1x'),
        2 => t('2x'),
        4 => t('4x'),
      ),
    );
    $form['advanced_settings_index'] = array(
      '#type' => 'select',
      '#title' => t('Advanced settings block'),
      '#description' => t('Select which block you\'d like to take the advanced settings from. Configure the <a href="@addressfield_staticmap">advanced settings</a>.', array(
        '@addressfield_staticmap' => url('admin/config/system/addressfield_staticmap'),
      )),
      '#default_value' => $settings['advanced_settings_index'],
      '#options' => array(
        0 => t('Map block type 1'),
        1 => t('Map block type 2'),
      ),
    );
  }
  return $form;
}

/**
 * Get the map type being used.
 */
function addressfield_staticmap_get_map_type($settings) {
  if (!array_key_exists('advanced_settings_index', $settings)) {
    return 'google_maps';
  }
  return variable_get('addressfield_staticmap_api_' . $settings['advanced_settings_index'], 'google_maps');
}

/*
 * Get the map size argument to use for a configuration.
 */
function addressfield_staticmap_get_size_args($settings) {
  $api = addressfield_staticmap_get_map_type($settings);
  if ($api == 'google_maps') {
    return $settings['map_size'] ? $settings['map_size'] : DEFAULT_MAP_SIZE;
  }
  return $settings['map_size'] ? $settings['map_size'] : '';
}

/*
 * Get the map size argument to use for a configuration.
 */
function addressfield_staticmap_get_size_description($settings) {
  $size = addressfield_staticmap_get_size_args($settings);
  if (empty($size)) {
    return 'Styled using CSS';
  }
  return $size;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function addressfield_staticmap_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  if ($display['type'] == 'addressfield_staticmap') {
    $summary = t('Zoom level: @zoom_level', array(
      '@zoom_level' => $settings['zoom_level'],
    ));
    $summary .= '<br/>';
    $summary .= t('Map size: @map_size', array(
      '@map_size' => addressfield_staticmap_get_size_description($settings),
    ));
    $summary .= '<br/>';
    $summary .= t('Prevent map zoom and scroll: @scroll_lock', array(
      '@scroll_lock' => $settings['scroll_lock'] ? t('Yes') : t('No'),
    ));
    if ($settings['additional']) {
      $additional_display = strlen($settings['additional']) > 60 ? substr($settings['additional'], 0, 60) . '...' : $settings['additional'];
      $summary .= '<br/>';
      $summary .= t('Additional parameters: @additional', array(
        '@additional' => $additional_display,
      ));
    }
    $summary .= '<br/>';
    $summary .= t('Show the address in text format: @text_address', array(
      '@text_address' => $settings['text_address'] ? t('Yes') : t('No'),
    ));
    $summary .= '<br/>';
    $summary .= t('Show the address in an info window: @info_window', array(
      '@info_window' => $settings['info_window'] ? t('Yes') : t('No'),
    ));
    $summary .= '<br/>';
    $summary .= t('Scale: @scale', array(
      '@scale' => isset($settings['scale']) ? $settings['scale'] : 1,
    ));
    $summary .= '<br/>';

    // Show the type name and not only the key.
    $map_style = array(
      'roadmap' => t('Roadmap'),
      'satellite' => t('Satellite'),
      'terrain' => t('Terrain'),
      'hybrid' => t('Hybrid'),
    );
    $summary .= t('Map style: @map_style', array(
      '@map_style' => $map_style[$settings['map_style']],
    ));
  }
  return $summary;
}

/**
 * Implements hook_field_formatter_view().
 */
function addressfield_staticmap_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  foreach ($items as $delta => $item) {
    $data_cleaned = array_filter($item);

    // If only the country is set, skip this (for some reason the country value
    // becomes mandatory if you limit the list).
    if (isset($data_cleaned['country']) && count($data_cleaned) <= 1) {
      continue;
    }
    $address = addressfield_staticmap_clean_address($item, $field['type']);
    $settings = array(
      'zoom' => $display['settings']['zoom_level'],
      'size' => addressfield_staticmap_get_size_args($display['settings']),
      'maptype' => $display['settings']['map_style'],
      'scale' => $display['settings']['scale'] ? $display['settings']['scale'] : 1,
      'index' => $display['settings']['advanced_settings_index'],
      'scroll_lock' => $display['settings']['scroll_lock'],
      'additional' => $display['settings']['additional'],
      'info_window' => $display['settings']['info_window'],
      'text_address' => $display['settings']['text_address'],
    );
    $api = variable_get('addressfield_staticmap_api_' . $settings['index'], 'google_maps');
    $settings['premier'] = variable_get('addressfield_staticmap_premier_' . $settings['index'], FALSE);

    // Display the address if the checkbox is set.
    if ($settings['text_address']) {
      $settings['text_address'] = _addressfield_staticmap_render_address($item);
    }
    if ($api !== 'mapquest' && $settings['premier']) {
      $settings['client_id'] = variable_get('addressfield_staticmap_premium_client_id_' . $settings['index'], '');
      $settings['crypto_key'] = variable_get('addressfield_staticmap_premium_crypto_key_' . $settings['index'], '');
    }
    else {
      $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $settings['index'], '');
    }
    if ($api != 'google_maps_api') {

      // Need a size specified for static map.
      $settings['size'] = empty($settings['size']) ? DEFAULT_MAP_SIZE : $settings['size'];
    }

    // Use Google Maps.
    if ($api == 'google_maps') {
      $settings['icon_url'] = variable_get('addressfield_staticmap_gmap_icon_url_' . $settings['index'], '');
      $settings['icon_url'] = empty($settings['icon_url']) ? 'color:green' : 'icon:' . $settings['icon_url'];
      $element[$delta]['#markup'] = _addressfield_static_map_render_google_maps_image($address, $settings, $entity);
    }
    elseif ($api == 'google_maps_api') {
      $settings['icon_url'] = variable_get('addressfield_staticmap_gmap_icon_url_' . $settings['index'], '');
      $settings['icon_url'] = empty($settings['icon_url']) ? 'color:green' : 'icon:' . $settings['icon_url'];
      $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $settings['index'], '');
      $entity_id_field = addressfield_entity_id_from_entity_type($entity);
      $settings['id'] = $entity->{$entity_id_field};
      $element[$delta]['#markup'] = _addressfield_static_map_render_google_maps($address, $settings, $entity);
    }
    elseif ($api == 'google_maps_embed') {
      $settings['icon_url'] = variable_get('addressfield_staticmap_gmap_icon_url_' . $settings['index'], '');
      $settings['icon_url'] = empty($settings['icon_url']) ? 'color:green' : 'icon:' . $settings['icon_url'];
      $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $settings['index'], '');
      $settings['id'] = $entity->{$entity_id_field};
      $element[$delta]['#markup'] = _addressfield_embed_map_render_google_maps($address, $settings, $entity);
    }
    elseif ($api == 'mapquest') {
      $settings['api_key'] = variable_get('addressfield_staticmap_api_key_' . $settings['index'], '');
      $element[$delta]['#markup'] = _addressfield_static_map_render_mapquest_image($address, $settings);
    }
  }
  return $element;
}

/**
 * Map size validator.
 *
 * @param array $element
 *   The element's render array.
 * @param array &$form_state
 *   The form state.
 * @param array $form
 *   The complete form render array.
 */
function addressfield_staticmap_mapsize_validate(array $element, array &$form_state, array $form) {
  if (!$element['#value']) {
    return;
  }
  $matches = array();
  $valid = FALSE;
  if (preg_match('/[Z0-9]*x[Z0-9]*/', $element['#value'], $matches)) {
    if ($matches[0] == $element['#value']) {
      $valid = TRUE;
    }
  }
  if (!$valid) {
    form_error($element, t('Invalid map size format. Please use format 123x456'));
  }
}

/**
 * Returns a Google Maps-friendly address from the Address Field format.
 *
 * @param array $address
 *   An array containing parts of the address to use.
 * @param string $field_type
 *   The type of field being processed.
 *
 * @return array
 *   A string containing the address, formatted for Google / Mapquest.
 */
function addressfield_staticmap_clean_address(array $address, $field_type = 'addressfield') {
  if ($field_type == 'addressfield') {
    $address = _addressfield_staticmap_render_address($address);

    // Remove newline from address prevents %0A in URL encode.
    $address = str_replace(array(
      "\r\n",
      "\r",
      "\n",
    ), ' ', $address);

    // Add some commas so that the address can still be parsed by Google Map's
    // API.
    $address = preg_replace('/(<\\/[^>]+?>)(<[^>\\/][^>]*?>)/', '$1, $2', $address);

    // Remove all HTML tags added by addressfield module.
    $address = strip_tags($address);
  }
  else {
    if ($field_type == 'location') {
      $location = $address;
      $address = array();
      $location_parts = array();
      if (isset($location['latitude']) && $location['latitude'] != 0 && isset($location['longitude']) && $location['longitude'] != 0) {
        $location_parts = array(
          'latitude',
          'longitude',
        );
      }
      else {
        $location_parts = array(
          'street',
          'additional',
          'city',
          'province',
          'postal_code',
          'country',
        );
      }
      foreach ($location_parts as $location_part) {
        if (!empty($location[$location_part])) {
          $address[] = $location[$location_part];
        }
      }
      $address = implode(', ', $address);
    }
  }
  return $address;
}

/**
 * Return the ID field name for a supplied entity.
 *
 * @param object $entity
 *   The entity to examine.
 *
 * @return null|string
 *   The matching ID field.
 */
function addressfield_entity_id_from_entity_type($entity) {
  if (empty($entity->base_type)) {
    return NULL;
  }
  $info = entity_get_info($entity->base_type);
  return isset($info['entity keys']['id']) ? $info['entity keys']['id'] : NULL;
}

/**
 * Helper function to render the address.
 *
 * @param array $address
 *   An array of parts of an address.
 *
 * @return string
 *   The rendered static map for the address.
 */
function _addressfield_staticmap_render_address(array $address) {

  // Set up some default arguments for addressfield_generate().
  $handlers = array(
    'address' => 'address',
  );
  $context = array(
    'mode' => 'render',
  );
  $address = addressfield_generate($address, $handlers, $context);
  return drupal_render($address);
}

/**
 * Implements hook_preprocess().
 */
function addressfield_staticmap_preprocess(&$variables, $hook) {
  if ($hook !== 'addressfield_staticmap_static_map' || is_null($variables['entity'])) {
    return;
  }
  $eid_field = addressfield_entity_id_from_entity_type($variables['entity']);
  if ($eid_field) {
    $hooks = array(
      'addressfield_staticmap_static_map__' . $variables['entity']->base_type,
    );
    if (isset($variables['entity']->type)) {
      $hooks[] = 'addressfield_staticmap_static_map__' . $variables['entity']->base_type . '__' . $variables['entity']->type;
    }
    $hooks[] = 'addressfield_staticmap_static_map__entity_' . $variables['entity']->{$eid_field};
    $variables['theme_hook_suggestions'] = array_merge($hooks, $variables['theme_hook_suggestions']);
  }
}

Functions

Namesort descending Description
addressfield_entity_id_from_entity_type Return the ID field name for a supplied entity.
addressfield_staticmap_block_info Implements hook_block_info().
addressfield_staticmap_block_view Implements hook_block_view().
addressfield_staticmap_clean_address Returns a Google Maps-friendly address from the Address Field format.
addressfield_staticmap_field_formatter_info Implements hook_field_formatter_info().
addressfield_staticmap_field_formatter_settings_form Implements hook_field_formatter_settings_form().
addressfield_staticmap_field_formatter_settings_summary Implements hook_field_formatter_settings_summary().
addressfield_staticmap_field_formatter_view Implements hook_field_formatter_view().
addressfield_staticmap_get_map_type Get the map type being used.
addressfield_staticmap_get_size_args
addressfield_staticmap_get_size_description
addressfield_staticmap_mapsize_validate Map size validator.
addressfield_staticmap_menu Implements hook_menu().
addressfield_staticmap_permission Implements hook_permission().
addressfield_staticmap_preprocess Implements hook_preprocess().
addressfield_staticmap_theme Implements hook_theme().
_addressfield_embed_map_render_google_maps Render regular Google Embed Map for a specific address.
_addressfield_staticmap_render_address Helper function to render the address.
_addressfield_static_map_render_google_maps Render regular Google Map for a specific address.
_addressfield_static_map_render_google_maps_image Render static Google Map image for a specific address.
_addressfield_static_map_render_mapquest_image Render static Mapquest image for a specific address.

Constants

Namesort descending Description
DEFAULT_MAP_SIZE @file Main file for the addressfield static map module.