0

I'm trying to create a pretty straightforward page with a Google map that I need to customize, but the code in the behavior isn't being run for some reason. Here's the code:

/**
 * Implementation of hook_theme
 */
function mymodule_theme() {
  return array(
    'affiliates_map' => array(
      'template' => 'affiliates-map',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'render element' => 'content',
     )
  );
}

/*
 * Page callback for map page.
 */
function mymodule_search_map() {
  drupal_add_css('
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }', array('group' => CSS_DEFAULT, 'type' => 'inline'));

  $path = drupal_get_path('module', 'mymodule');
  $gmap_api_key = variable_get('affiliates_gmap_api_key', '');
  drupal_add_js('//maps.google.com/maps/api/js?v=3&key=' . $gmap_api_key . '&callback=initMap',  array('type' => 'external'));
  drupal_add_js($path . '/js/mymodule.js', array('type' => 'file', 'weight' => 6, 'scope' => 'footer'));

  $output = theme('affiliates_map');

  return $output;
}

Here's my theme template.

<?php
/**
 * @file
 *   This template handles the display of the affiliates map.
 */
?>

<h2>Map content goes here</h2>

<div id="naa-map"></div>

and the js file

(function($) {
  Drupal.behaviors.affiliatesMap = {
    attach: function (context, settings) {
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('naa-map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 14
        });
      }
    }
  };
}(jQuery));

My console is giving me an error about initMap() not being found, and when I put a breakpoint in the behavior in initMap, it doesn't get hit. What am I doing wrong that it's not finding the behavior code? I've mimicked the Location Map module, and it works fine, so I'm not sure where I went wrong.

Thanks.

2 Answers 2

1

The issue ended up being my CSS. I was using styles from the sample page that had a height of 100%. Once I added some height and width to my naa-map div, my map showed up fine.

0

I think you should not declare initMap inside of the anonymous attachment - cause it's not visible outsinde. Try it like

(function($) {
  Drupal.behaviors.affiliatesMap = {
    attach: function (context, settings) {
      function initMap();

    }
  };
}(jQuery));

var map;

function initMap() {
    map = new google.maps.Map(document.getElementById('naa-map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 14
    });
}

But I think it's anyway not so nice with that global space "var map".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.