Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I think this is a silly question, but I can't seem to find the "right" keyword to use in searching the forums. Anyway

I'm using the google maps API on my website regarding restaurants. The map loads when a restaurant has been selected. I was initially using the google embed map but some errors are happening like markers not showing, etc so I switched to gm API.

Question is, how do I use a drupal.setting variable to a javascript? Here's my code

var myCenter=new google.maps.LatLng(Drupal.settings.eatery_geo.address);
    function initialize()
    {
    var mapProp = {
      center:myCenter,
      zoom:16,
      mapTypeId:google.maps.MapTypeId.ROADMAP
      };

    var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);

    var marker=new google.maps.Marker({
      position:myCenter,
      });

    marker.setMap(map);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

Where Drupal.settings.eatery_geo.address has the variable?

This seems to not work, only showing a blank div.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

It gets its value from your PHP code. Here is an example of use:

//Your module.php
$settings = array(
  'helloWorld' => array(
    'display' => 'alert',
    'message' => 'Hello World!',
  ),
);
drupal_add_js($settings, 'settings');

You can access the message in your JavaScript with Drupal.settings.helloWorld.message.

share|improve this answer
    
oh alright, so that's how you do it. thanks! –  Kronk by the minute Nov 13 '14 at 4:07

I was receiving the following error:

Warning: Illegal offset type in drupal_add_js() (line 4230 of /var/www/drupal/includes/common.inc).

Changing the word 'settings' to 'setting' in the drupal_add_js() line seemed to fix it for me:

 <?php

 $settings = array(
   'helloWorld' => array(
     'display' => 'alert',
     'message' => 'Hello World!',
   ),
 );
 drupal_add_js(array('my_custom_module_name' => $settings), 'setting');

I put the above code in a custom module, let's call it my_custom_module_name for this example.

Then put the following in my javascript file:

Drupal.behaviors.my_custom_module_name = {
  attach: function(context, settings) {

    // Place your code here.
    // alert(Drupal.settings.my_custom_module_name.helloWorld.message);
    console.log(Drupal.settings.my_custom_module_name.helloWorld.message);

  }
};

Make sure your_theme_name.info references your js file in order for it to load, for example:

scripts[] = js/script.js
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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