New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Start learning with our library of video tutorials taught by experts. Get started

Drupal 7 Custom Module Development
Illustration by

Adding a Google Map using theming


From:

Drupal 7 Custom Module Development

with Jon Peck

Video: Adding a Google Map using theming

I imported wind farms from the Open Energy Information Initiative and I can now view each node of content type wind farm. I hid the latitude and longitude because there was no need to show it to the user in this context. However, this view is uninteresting. Having a map with a marker indicating where the wind farm is has a positive impact on the user. To do this, I'm going to inject an element into the full view of the node and make a custom function for displaying the element. By providing this functionality within the custom module, I am allowing themers to override or customize the base functionality I provided.

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Drupal 7 Custom Module Development
2h 57m Advanced Oct 16, 2012

Viewers: in countries Watching now:

Extend your Drupal 7 sites with custom modules, which allow you to create everything from admin interfaces to forms. Author Jon Peck describes how modules extend your base Drupal installation, then walks through how to write your own module with a practical example featuring geo-positioned alternative energy centers. The course also describes how to control access to site features, create new content types, build forms, understand data persistence, embrace coding standards, and much more.

Topics include:
  • Creating your first module
  • Interacting with hooks
  • Working with permissions and roles
  • Controlling access
  • Adding a menu item to an admin interface
  • Using the Form API (FAPI) to quickly create a form
  • Creating custom form validation
  • Manually creating a custom content type
  • Validating user input
  • Importing content using feeds
  • Creating a block
  • Understanding best practices and coding standards
Subjects:
Developer Web CMS Blogs Web Design Programming Languages Web Development
Software:
Drupal
Author:
Jon Peck

Adding a Google Map using theming

I imported wind farms from the Open Energy Information Initiative and I can now view each node of content type wind farm. I hid the latitude and longitude because there was no need to show it to the user in this context. However, this view is uninteresting. Having a map with a marker indicating where the wind farm is has a positive impact on the user. To do this, I'm going to inject an element into the full view of the node and make a custom function for displaying the element. By providing this functionality within the custom module, I am allowing themers to override or customize the base functionality I provided.

I will not be theming or designing the look and feel of the entire node view. That's out of the scope of this course, and we'll be better explored in depth on its own. I'm going to add a map using the Google Maps JavaScript API Version 3 which allows developers to embed Google Maps into web pages. It's fast, flexible and free for websites that are free to consumers. However, I don't want to spend the time learning all the ins and outs of the JavaScript API as I want to focus on delivering features.

I search the contributed modules and found GMap3 Tools, a module that allows a developer to quickly add a Google Map by providing an API made explicitly for Drupal. It's minimal and functional so it fulfills my needs. Open the IDE and then go to windfarms.module and navigate to the end. The first thing I will do is implement hook_node_ view, which acts on the node that is being assembled before rendering, hook_node_view, function windfarms_node_view takes three parameters, the node, the view_mode and the language code.

This function will be accessed on every node view, so unless I give it context, it's going to try to put a map on every page. I only want to put the map on the full view of the windfarm content type. If ($node-> type == 'windfarm' && $view_mode == 'full'. When rendering a node, Drupal builds a structured array keyed with the element name. This markup is in the same structure as the form API and is placed in the content property of the node.

I'm going to create a new element called windfarm_ gmap in the content property, $node->content and as this is a structured array, I will access it by key 'windfarm_gmap' = array. I'm going to use hash tag markup to indicate that the contents of this element are just pre-rendered HTML. I'm going to call the theme function to create the contents. The theme function generates themed output by examining what was requested and determines what is the right theming option or template.

Theme takes two parameters: the name of the hook, then an optional array of parameters that will be passed to the theming target. I'm going to create a theme function for windfarm_ gmap, so I'll stick with the name, and I'll pass the node itself to the theme function with key node. Weight is used to determine the order in which something is displayed. The higher the weight, the heavier it is and heavy things sink. Weight is used in the form API and menu API among other places. In this context, I'm going to use weight to ensure that the Google Map is the last thing to be shown by setting it to the maximum 100, so #weight is 100.

The next thing I need to do is tell Drupal about the custom theme function and the arguments it takes. I'll do that by implementing hook theme which registers the custom themes with Drupal. Hook_theme takes four parameters: function windfarms_theme, existing, type, theme and path.

I won't actually need any of them for what I'm doing, but as they required by the hook, I must define them. Hook_theme returns an array keyed by the name of the theme function and some options. I need to specify that variables will be made available to the theme function, so I'll provide the structure; return array containing windfarm_ gmap and a nested array, specify the variables which will just be the node which will default to null.

Now that the hook_theme has been implemented, let's create the theme function itself. Theme functions don't implement anything, hooks are otherwise. They just return a string with the output. Start with a doc block, Wind Farm Google Map theme function. By naming convention, theme functions must start with theme_windfarm_gmap which takes variables the array that was created earlier.

Let's get some introspection into variables, dpm($ variables), save to file, then go back to the browser. Drupal's theme registry, the internal structure for determining what themes what, is heavily cached to improve site performance, therefore the cache will need to be cleared in order to see the changes. Go to Configuration > Development and click on Performance, so you can clear all caches.

Go back to the homepage and view one of the Wind Farms nodes. Now there's debugging information shown at the top of the page as an array with one element node. The title is shown as is, but the body, latitude and longitude are the nested arrays with the language undefined. Now that I know what the structure of the node is, I can access those elements to add the Google Map. Return to the IDE and remove the debugging information.

The first thing that needs to be done is to check if the Google Map has been enabled in the admin interface. If not, just return. Check to see if the Google Map is enabled; if not variable_get and the name is windfarms_gmap; if not, then just return. Next, I'll check to see if I have the right information needed to display the map. In particular, both latitude and longitude are needed, so $lat = $variables 'node'. I'm going to access windfarm_latitude, LANGUAGE_NONE, 0 and then 'value'.

The longitude will be just about the same, add a comment, Cannot render map without both latitude and longitude, if lat is equal to the empty string or long is equal to the empty string, then return.

Now that I'm confident that I have all the context needed, I can start building the map using the GMap3 Tools module. Three basic steps are needed. First, load the include file, second create the map with the configuration array, then third, add the element that will be populated with the map by ID. First, I'll include the module using the Drupal function module_load_include, which loads the module include file. It takes the file extension, the name of the module and optionally the base filename.

So module_load_include, and let's include file and module is gmap3_tools. I'm going to need two more things from the windfarm node, the facility name and the description which I will use to populate the marker on the map. As this is user supplied input, I don't trust it, as it may contain content other than plain text, which will at best possibly break the map and at worse, contain malicious code.

Drupal provides mechanism for encoding special characters in a plain text string for HTML display using the function check_plain which takes the string as a parameter and returns the sanitized result, $facility_ name = check_plain ($variables 'node' -> title); $description = check_plain (variables 'node' -> body, LANGUAGE_NONE, 0 and then the key 'value'.

Next, I'll call a function from the GMap3 Tools library to add the map via JavaScript. It takes a configuration array which I will define in-line and doesn't return anything. There's no need to learn all of the options and functions for the GMap3 Tools library as I'm using it as an example. Different modules have different API implementations gmap3_tools_add_map, then I will create an empty array.

First, I'll set the mapID which is the name of the element that will be populated using JavaScript. I'll set it to 'gmap-canvas-' $variables 'node'->nid, which will allow multiple maps to be shown at one time. Next, I'll set the mapOptions. This is an array. I will set the zoom from the variables set from the configuration page variable_get ('windfarms_default_gmap_zoom').

The next one will be the mapTypeId where I will specify the use of a satellite map rather than a roadmap, so the windfarm can be actually seen, GMAP3_TOOLS_MAP_TYPE_ID_SATELLITE. To add a marker to the map, set markers to an array populated with a helper function gmap3_tools_create_marker, which takes four parameters, the latitude, the longitude, the title, which I will set to the facility name and the content which I will set as the description.

The last configuration is the default position of the markers in gmap3ToolsOptions, defaultMarkersPosition, which I will set to GMAP3_ TOOLS_ DEFAULT_POSITION_CENTER. Now that the JavaScript has been injected, specify a target for the map. Use the same identifier as we specified in gmap3_tools_add_map, 'gmap-canvas-' . $ variables 'node' ->nid.

I'll set the width to 500 pixels and the height to 400 pixels and then close the div. Finally, return the theme output, save, then return to the browser and refresh the page. The Google Map has now shown with a marker, hovering will show a title and clicking will show the description. Now that I've added a Google Map to the node view, I'd like to create a map that shows a number of wind farms on a map that allows you to get more information about them.

Find answers to the most frequently asked questions about Drupal 7 Custom Module Development.


Expand all | Collapse all
please wait ...
Q: gmap3_tools is not working the way I expected it to. What version of gmap3_tools should I be using?
A: Use the free exercise file containing the version of gmap3_tools used for recording; the published version of the module on drupal.org has changed since recording and is not backwards compatible.
Q: I attempted to run the Drupal site root from the project files, but the site isn't loading. Why not?
A: The Drupal configuration file in sites/default/settings.php contains database configuration specific to the environment used to record the movie. This may be different than your environment. Edit the file and search for "windfarms" - you may need to change the database host, username, password, db name and port to match your specific environment.
 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Drupal 7 Custom Module Development.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.