Как сделать, чтобы карта раскрывалась через ссылку

Главные вкладки

Комментарии

Аватар пользователя snegin snegin 22 января 2014 в 14:44

В page--node--article.tpl.php я добавил код

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Примеры. Создание карты по требованию.</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
         <!--
           Подключаем API карт 2.x
           Параметры:
           - load=package.full - полная сборка;
                - lang=ru-RU - язык русский.
                Если вы используете API локально, то в URL ресурса необходимо указывать протокол в стандартном виде (http://...)
        -->
        <script src="//api-maps.yandex.ru/2.0/?load=package.full&lang=ru-RU"
           type="text/javascript"></script>
        <!--
           Основная библиотека JQuery.
           Яндекс предоставляет хостинг JavaScript-библиотек:
       -->
        <script src="http://yandex.st/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
    </head>

    <body>
        <input type="button" value="Показать карту" id="toggle"/>
        <p>
            <div id="map" style="width: 400px; height: 300px"></div>
        </p>
    </body>
</html>

Появилась форма открыть карту. Она не работает. Теперь нужно создать файл .js. Добавить туда код.

// Как только будет загружен API и готов DOM, выполняем инициализацию
ymaps.ready(init);

// Инициализация и уничтожение карты при нажатии на кнопку.
function init () {
    var myMap;

    $('#toggle').bind({
        click: function () {
            if (!myMap) {
                myMap = new ymaps.Map('map', {
                    center: [55.010251, 82.958437], // Новосибирск
                    zoom: 9
                });
                $("#toggle").attr('value', 'Скрыть карту');
            }
            else {
                myMap.destroy();// Деструктор карты
                myMap = null;
                $("#toggle").attr('value', 'Показать карту снова');
            }
        }
    });
}

Куда помещается файл? Какое имя ему задается?.

Потом я скачал модуль Яндекс-Мар, установил, создал поле. Вывелась карта. Но как заставить работать форму?

Аватар пользователя snegin snegin 23 января 2014 в 15:16

Я удалил содержимое прежнего ява-скрипта в модуле Яндекс-маp. И поставил код скрипта из песочницы Яндекс. Модулем и отдельным скриптом вывести не получается. Карта появилась во Views. Но у меня пропала возможность добавлять маркеты в админке. Нужно соединить добавленный код скрипта (вот он)

/**
 * @file
 * Map support
 */

 
 // Как только будет загружен API и готов DOM, выполняем инициализацию
ymaps.ready(init);

// Инициализация и уничтожение карты при нажатии на кнопку.
function init () {
    var myMap;

    $('#toggle').bind({
        click: function () {
            if (!myMap) {
                myMap = new ymaps.Map('map', {
                    center: [55.010251, 82.958437], // Новосибирск
                    zoom: 9
                });
                $("#toggle").attr('value', 'Скрыть карту');
            }
            else {
                myMap.destroy();// Деструктор карты
                myMap = null;
                $("#toggle").attr('value', 'Показать карту снова');
            }
        }
    });
}
 
 
 
 
 

С тем кодом, который я удалил

<?php
/* Define $root as a global variable */
global $root;
$theme_root = base_path() . path_to_theme();
$root = base_path() . drupal_get_path('theme', 'montreal');

include_once(drupal_get_path('theme', 'montreal').'/includes/init.php');

function montreal_preprocess_page(&$vars, $hook) {
 if (isset($vars['node'])) {
   $suggest = "page__node__{$vars['node']->type}";
    $vars['theme_hook_suggestions'][] = $suggest;
  }
 
  $status = drupal_get_http_header("status");  
  if($status == "404 Not Found") {      
    $vars['theme_hook_suggestions'][] = 'page__404';
  }
   
}

/* Assign top level menu list items an ascending class of menu_$number  */
function montreal_menu_link(array $variables) {
  unset($variables['element']['#attributes']['class']);
  $element = $variables['element'];
  static $item_id = 0;
  $menu_name = $element['#original_link']['menu_name'];

  if ($element['#below']) {
    $element['#attributes']['class'][] = 'dropdown';
  }
 
  if ($element['#href'] == '<front>' && drupal_is_front_page()) {
   $element['#attributes']['class'][] = 'active-trail';
  }
 
  $sub_menu = $element['#below'] ? drupal_render($element['#below']) : '';
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . '</li>';
}

/* Allow sub-menu items to be displayed */
function montreal_links($variables) {
  if (array_key_exists('id', $variables['attributes']) && $variables['attributes']['id'] == 'main-menu-links') {
        $pid = variable_get('menu_main_links_source', 'main-menu');
        $tree = menu_tree($pid);
        return drupal_render($tree);
  }
  return theme_links($variables);
}

/* Add a comma delimiter between field tags*/
function montreal_field($variables) {
 
  $output = '';
 
  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
   
  }
 
  // Render the items.
 

  if ($variables['element']['#field_name'] == 'field_tags') {
    // For tags, concatenate into a single, comma-delimitated string.
    foreach ($variables['items'] as $delta => $item) {
      $rendered_tags[] = drupal_render($item);
    }
    $output .= implode(' / ', $rendered_tags);
  }
 
  elseif ($variables['element']['#field_name'] == 'field_image') {
    // For tags, concatenate into a single, comma-delimitated string.
    foreach ($variables['items'] as $delta => $item) {
      $rendered_tags[] = drupal_render($item);
    }
    $output .= implode(', ', $rendered_tags);
  }
 
  elseif ($variables['element']['#field_name'] == 'field_second_image') {
    // For tags, concatenate into a single, comma-delimitated string.
    foreach ($variables['items'] as $delta => $item) {
      $rendered_tags[] = drupal_render($item);
    }
    $output .= implode(', ', $rendered_tags);
  }

 
  elseif ($variables['element']['#field_name'] == 'field_basic_portfolio_categories') {
    // For tags, concatenate into a single, comma-delimitated string.
    foreach ($variables['items'] as $delta => $item) {
      $rendered_tags[] = drupal_render($item);
    }
    $output .= implode(', ', $rendered_tags);
  }
 
  elseif ($variables['element']['#field_name'] == 'field_portfolio_image') {

    // For tags, concatenate into a single, comma-delimitated string.
    foreach ($variables['items'] as $delta => $item) {
      $rendered_tags[] = drupal_render($item);
    }
    $output .= implode(', ', $rendered_tags);
  }
   
  else {
    // Default rendering taken from theme_field().
    foreach ($variables['items'] as $delta => $item) {
      $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
      $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
    }
  }
 
  // Render the top-level DIV.
   
  return $output;
}

/* Put Breadcrumbs in a ul li structure and add descending z-index style to each <a href> tag */
function montreal_breadcrumb($variables) {
  $count = '100';
  $breadcrumb = $variables['breadcrumb'];
  $crumbs = '';

  if (!empty($breadcrumb)) {
   
    foreach($breadcrumb as $value) {
      $count = $count - 1;
      $style = ' style="z-index:'.$count.';"';
      $pos = strpos( $value, ">");
      $temp1=substr($value,0,$pos);
      $temp2=substr($value,$pos,$pos);
      $crumbs = $value.'/ ';
    }
 
  }
  return $crumbs;
}

/* Add various META tags to HTML head. */
function montreal_preprocess_html(&$vars){
 global $root;
  $meta_title = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#weight' => 1,
    '#attributes' => array(
      'name' => 'title',
      'content' => theme_get_setting('seo_title')
    )
  );
 
  $meta_description = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#weight' => 2,
    '#attributes' => array(
      'name' => 'description',
      'content' => theme_get_setting('seo_description')
    )
  );
 
  $meta_keywords = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#weight' => 3,
    '#attributes' => array(
      'name' => 'keywords',
      'content' => theme_get_setting('seo_keywords')
    )
  );
 
  $font = array(
    '#tag' => 'link',
    '#weight' => 4,
    '#attributes' => array(
      'href' => 'http://fonts.googleapis.com/css?family=Open+Sans',
      'rel' => 'stylesheet',
      'type' => 'text/css',
    ),
  );
 
  $condensed= array(
    '#tag' => 'link',
    '#weight' => 5,
    '#attributes' => array(
      'href' => 'http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300',
      'rel' => 'stylesheet',
      'type' => 'text/css',
    ),
  );

  $color = array(
    '#tag' => 'link',
    '#weight' => 6,
    '#attributes' => array(
      'href' => ''.$root.'/css/colors/'.theme_get_setting('color_scheme').'.css',
      'rel' => 'stylesheet',
      'type' => 'text/css',
      'media' => 'screen',
    ),
  );
 
  $viewport = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#weight' => 7,
    '#attributes' => array(
      'name' => 'viewport',
      'content' =>  'width=device-width, initial-scale=1',
    )
  );
 
  $font_family = array(
    '#type' => 'markup',
    '#markup' => "<style type='text/css'>body {font-family:".theme_get_setting('font_family')." !important;}</style> ",
    '#weight' => 8,
  );
   
  if (theme_get_setting('seo_title') != "") {
    drupal_add_html_head( $meta_title, 'meta_title' );
  }
   if (theme_get_setting('seo_description') != "") {
    drupal_add_html_head( $meta_description, 'meta_description' );
  }
  if (theme_get_setting('seo_keywords') != "") {
    drupal_add_html_head( $meta_keywords, 'meta_keywords' );
  }
 
  if (theme_get_setting('enable_boxed_layout') == "1") {
    drupal_add_html_head( $box_layout, 'box_layout' );
  }

  drupal_add_html_head( $font, 'google_font_open_sans' );
  drupal_add_html_head( $condensed, 'google_font_condensed' );
  drupal_add_html_head( $viewport, 'meta_viewport' );
  drupal_add_html_head( $font_family, 'font_family');
 
}

/* Separate from montreal_preprocess_html so function can be called directly before </head> tag. */
function montreal_user_css() {
  echo "<!-- User defined CSS -->";
  echo "<style type='text/css'>";
  echo theme_get_setting('user_css');
  echo "</style>";
  echo "<!-- End user defined CSS -->";
   
}

?>