Few Drupal sites are built without the Views module, and Views underlies much of the mapping in Drupal. This chapter explores different ways of displaying spatial data, primarily through the Google and OpenLayers JavaScript mapping APIs, but also using lists, tables, and data feeds.
There are two main choices for displaying maps in Drupal: the OpenLayers JavaScript library and the GMap moduleâs implementation of the Google Maps API. This chapter covers how to create maps with both modules.
The GMap module is the more straightforward to understand. It contains code to pull data from your Drupal website and display it on a Google Map. Continuing our earlier example, this will be a map of Drupal companies.
The OpenLayers module for Drupal does a similar thing, but it uses a different JavaScript API to display the map, and it allows you to choose from several different base tile sets, including sets from Google Maps, OpenStreetMap, Bing, and more. Continuing our earlier example, this will be a map of Drupal user groups.
OpenLayers is a JavaScript library for displaying maps. It is a free, open source project, which means that you can use the maps you create in any way that you want and that, if youâre so inclined, you can help improve the code. At the most basic level, the OpenLayers module allows maps to be displayed on a Drupal website. The module provides a way to configure the appearance of maps and to choose behaviors for the maps. The display of the data on the map is done by integrating with the Views module. Each of these steps is outlined below.
Download the latest release of the OpenLayers module for Drupal 7 to your siteâs contributed modules directory. You will also need the Chaos Tools module and the Views module, as they are required by OpenLayers.
Enable all three modules that come with OpenLayers (Figure 4-1). The OpenLayers UI module provides a user interface for configuring your maps and can be disabled once work is complete on your site. The OpenLayers Views module integrates OpenLayers with the Views module. The Chaos Tools module, Views module, and Views UI module must also be enabled.
Configure permissions for OpenLayers by following the âPermissionsâ link on the Modules page, or by going directly to the Permissions page at admin/people/permissions. There is only one permission, âAdminister OpenLayers,â which should only be given to trusted administrators. You do not want normal users of your site to change the appearance and behavior of the maps on your site.
In the OpenLayers module, a map is a combination of three things: layers of data (such as map tiles or markers), styles that are applied to some of these layers, and behaviors (interactions that are attached to maps). OpenLayers uses the Views module in two ways: first to create data layers to display on the map, as a map is a set of layers, and second to display the final map as a block or page. We start this exercise by creating a layer using Views, and then will use Views again to create the final map.
Note
This is the place where most users get confused with the OpenLayers module, and rightfully so. The module uses Views twice. This means that you will have to go to the Views interface, back to the OpenLayers interface, and back to Views. The goal is to change this in future versions of the OpenLayers module so that the user experience is more intuitive.
Layers can be put into two categories. The base layer contains the underlying map, which is usually the tile set, such as MapQuestâs Open Aerial tiles; there is only one of these displayed at a time. The overlay layers contain all your added data, such as icons marking businesses, compost facilities, or public toilets; there can be multiple overlay layers displayed on one map. The base layer can be thought of as the map layer; the overlay layer can be thought of as the data layer.
The OpenLayers module comes with several map layers, including four types of Google map tiles (normal, satellite, hybrid, and physical), three types of Yahoo! map tiles (satellite, street, and hybrid), three types of Bing map tiles (satellite, street, and hybrid), and four types of OpenStreetMap tiles. You can see these on the Layers Configuration page at admin/structure/openlayers/layers. Other Drupal modules, such as MapBox, add even more map layers. Adding further map layers is discussed in Chapter 6. For the examples in this chapter we are just going to use one of the default map layers.
The data overlays are more critical to understand because this is where you will be able to add your Drupal data and then put it on a map. By utilizing Views, you can create many data overlays to go on a single map. Data overlays can also come from an external source, such as a KML file, but this is managed through the OpenLayers Layers interface.
To summarize, there are four stages in creating a map using the OpenLayers module:
Create a data layer to receive the user-supplied data about Drupal groups.
Create a Map to display this data layer over a map layer.
Create a page to display your Map.
Tweak the Styles and Behaviors to beautify how your data appears on your Map.
The most common way to create a data layer is using the Views module. In Geofield Module we created some Drupal user groups. We will use Views and OpenLayers to display all of these on a map.
From the Views page add a new view, admin/structure/views/add.
For the âView name,â enter
Drupal groups
.Tick the âDescriptionâ checkbox and enter this description:
Drupal
groups
data
layer for a map
. This description will show up later in the user interface and is helpful there.In the âShowâ section, leave âContentâ selected from the first drop-down. Change the âtypeâ drop-down to âUser Group.â Leave the âsorted byâ drop-down set to âNewest first.â
Note
If you do not see the âUser Group,â make sure that you created this content type in Geofield Module.
Uncheck the âCreate a pageâ checkbox. At this stage we are creating a data layer, not a page or block.
Click the âContinue & editâ button.
Click the âAddâ button (circled in red in Figure 4-2) and click on âOpenLayers Data Overlayâ from the list of displays that shows.
Enter a Title for the View, such as
Drupal groups data layer
.Note
The Views module allows you to create multiple displays in one View. In this example we are only creating an âOpenLayers Data Overlayâ display. Other displays include a Page, Block, or Feed. If you have multiple displays in one view, you need to be aware of whether you are changing a setting for one display or all displays. For simplicity, we will only have one display in this View, so for this and all following settings the changes that you make can be applied to all displays.
In the âFieldsâ section of the Views configuration form we need to add the fields that contain the location information for our âUser Groupâ content type. This is the information that OpenLayers is going to extract from our stored data, interpret, and use to display the data layer of our map. Click the âaddâ button (circled in red in Figure 4-3).
On the list of fields that shows, find the field labelled âContent: Group locationâ and select it, then click the âAdd and configure fieldsâ button, shown in Figure 4-4.
On the âConfigure fieldâ screen that comes up next, untick the âCreate a labelâ option. Tick âExclude from display.â All other settings can stay the same. Click the âApply (all displays)â button to save the configuration.
Back on the âOpenLayers Data Overlay detailsâ screen we need another field. This time, add the âContent: Bodyâ field. This one will contain the user-supplied descriptions of all our Drupal user groups. Click the âApply (all displays)â button to save the configuration.
By adding these fields, we now have all the data necessary to create our data layer, but OpenLayers does not yet know which of these fields contain the spatial data and which fields are merely descriptive.
Back on the âOpenLayers Data Overlay detailsâ screen under the âFormatâ heading, click on the âUnformatted listâ link (circled in red in Figure 4-5). Select the only radio button available, âOpenLayers Data Overlay,â and click the âApply (all displays)â button to save.
On the Style options screen that loads next, change the âMap Data Sourcesâ drop-down to WKT. In the âWKT Fieldâ that appears below, select the field that contains the WKT value, âGroup location.â In âTitle Field,â choose âTitleâ in the drop-down. In âDescription Field,â select âBody.â Click the âApply (all displays)â button to save.
Back on the âOpenLayers Data Overlay detailsâ screen again, one last setting to change is the pager. The Views module is normally used to create lists of content, such as âmy 10 most recent blog posts.â The pager is used there to let people read through all the older blog posts. For our map, we want to show more than 10 places. Under âItems to display,â click the â10 itemsâ link. On the screen that loads, change âItems to displayâ to
100
. Click the âApply (all displays)â button to save.Note
See Browser Capabilities on why to avoid displaying an unlimited amount of data.
The View that creates the data layer for the map is now complete. Click the âSaveâ button on the top right.
There is now a data layerâbut as yet, no underlying map! So now, finally, we must choose some mapping to form our map (base) layer and combine it with our data layer to form a Drupal âMap.â
The next step is to create what the OpenLayers module refers to as a âMap.â To distinguish this from all the other things referred to as maps, however, we will refer to it as a âMap Configuration,â because this is where we will define the combinations of layers, styles, and behaviors that constitute a map. On the OpenLayers Maps page at admin/structure/openlayers/maps there are several default Map Configurations: one that comes with the OpenLayers module, and two that are added by the Geofield module. We will create a new Map Configuration to display our âDrupal user groupâ data layer.
Note
In OpenLayers in Drupal 6, Map Configurations were called âpresets.â
Add a new Map Configuration at admin/structure/openlayers/maps/add.
Enter a name for this Map Configuration. It will be used internally by Drupal to store the Map Configuration, so it should be lowercase characters, numbers, or underscores (e.g.,
user_groups
).Enter a title and a description for this Map Configuration. These will be seen by you in other parts of the user interface, so make them descriptive (e.g.,
Drupal user groups
andA map of Drupal user groups around the world
).Most of the other values in this âGeneral informationâ tab should remain with the default values, though change the Height to
500px
. It is often useful to leave the width atauto
; this will make the map fill the full width of the page. We will cover the use of the âImage Pathâ and âCSS Pathâ in The Map Interface.Before clicking the âSaveâ button, take a look at the configuration options in the other tabs on this page. First click on âCenter & Bounds.â
The âCenter & Boundsâ tab contains the defaults for the centerpoint and zoom level for the map, and provides a map interface to change these values. Leave these at the default values for now.
The âLayers & Stylesâ tab is where OpenLayers pulls in the data layer that was created in OpenLayers layers. The âMap Projectionâ and âDisplay Projectionâ sections can be left unchanged. From the list of âBase layersâ (the map layers), choose âOSM Mapnikâ as the default and tick the âEnabledâ checkbox.
Still in the âLayers & Stylesâ tab, go to the âOverlay layersâ table. Tick the âEnabledâ and âActivatedâ checkboxes for your âDrupal groups data layerâ layer.
Note
You set the title of the âDrupal groups data layerâ in Step 8.
Finally, click on the âBehaviorsâ tab. This configures the interactive elements of the map. We will discuss the various behaviors in more detail in Exploring OpenLayers Behaviors, but for now just tick the Attribution, Popup, Navigation, and PanZoomBar checkboxes. When you click the Popup checkbox, an option will open below to select which layer will contain the data for the pop ups. Here, tick the box labelled âdrupal_groups_openlayers_1,â as this is the data layer that was enabled in the previous step.
Note
You may have to save the Map Configuration before the âdrupal_groups_openlayers_1â option shows under the Popup behavior. This is because the interface is not AJAX-enabled and does not know yet that you have enabled that layer.
Click the âSaveâ button to save your Map Configuration. It will now show in the list of OpenLayers maps at admin/structure/openlayers/maps.
We now have a Map Configuration and need a way to display the map on a page of the website.
The simplest way to display an OpenLayers map uses the Views module. The View creates a page that uses the Map Configuration from the previous step .
Add a new View at admin/structure/views/add.
For the âView name,â enter
Map of Drupal groups
.Leave the âCreate a pageâ checkbox ticked, and leave the default Page title and Path.
Change the first âDisplay formatâ drop-down to âOpenLayers Mapâ.
Click the âContinue & editâ button.
On the âPage detailsâ configuration page, under âFormatâ (circled in red in Figure 4-6), click on the âSettingsâ link.
In the âMapâ drop-down, select âDrupal user groups.â Click the âApply (all displays)â button to save.
Click the âSaveâ button on the top right to save the view and create the map display.
On the right of the page is a âview pageâ button. Click this to view the map. It should look something like Figure 4-7. You can see an example of this online.
If you click on the marker for one of the Drupal user groups, you will see a pop up open with the name of the group and its description. If the person adding the information has entered a long description, the pop up will be really wide and might go off the edge of the map, as shown in Figure 4-8. If you want a long description, it is possible to make the pop up narrower using CSS. Alternatively, the description can be truncated in the View configuration. Edit the view that contains the data layer at admin/structure/views/view/drupal_groups/edit. Under the âFieldsâ section, click on âContent: Body (Body).â Expand the âRewrite resultsâ section. Tick the âTrim this field to a maximum lengthâ checkbox. In the âMaximum length,â enter
60
(which will be 60 characters). Leave all other options as their defaults. Click the âApply (all displays)â button to save. Click the âSaveâ button on the top right again.
We now have a map that displays Drupal user groups, but an orange dot on the map isnât a particularly inspiring representation of a Drupal group. The next section will allow customization of styles on the map.
OpenLayers styles provide a way to determine the appearance of geographic data: for example, the color and thickness of lines, the radius of points, or the opacity of polygons. Styles can be icons or markers, as well as simple geometric shapes like a circle. The OpenLayers module comes with some default styles, which can be seen at admin/structure/openlayers/styles. We will add a new style of dot to display the Drupal user groups that are being displayed on our map.
From the OpenLayers moduleâs âStyles configurationâ page, add a new Style at admin/structure/openlayers/styles/add.
Enter a name for this Style. The name will be used internally by Drupal to store this Style, so should be lowercase with underscores instead of spaces (e.g.,
blue_dots
).Enter a title for this Style (e.g.,
Blue dots
).There are lots of choices for Styles, each explained on the page. Most can be left unchanged for this example. The first one to change is âpointRadius.â Our Drupal user groups show as points on the map, so we need to set the size in pixels for the point. Set it to
5
.âfillColorâ is the hexadecimal value of the color that will fill the circle where there is a Drupal user group. Enter
#53b0eb
, which is the shade of blue used commonly in Drupalâs branding.âstrokeColorâ is the color of the line surrounding the circle. Enter
#0678be
, a darker blue.âstrokeWidthâ is the thickness of the line surrounding the circle. Leave this at
1
.âfillOpacityâ determines if the circle that represents the user group location is transparent or opaque. The default value of 1 means that it is opaque. Change this to
0.8
to make it slightly transparent.âstrokeOpacityâ determines the opacity or transparency of the line surrounding the circle. Leave this at
1
.Save this new Style. It will show in the list of OpenLayers styles at admin/structure/openlayers/styles.
To use this Style on the map of Drupal user groups, we need to update the Map Configuration from OpenLayers Maps.
From the OpenLayers moduleâs maps page at admin/structure/openlayers/maps, click the edit link for the âDrupal user groupsâ map.
Click on the âLayers & Stylesâ tab.
In the âOverlay Layersâ table, find the âDrupal groups data layer.â Change the Style drop-down to the âBlue dotsâ style that you just created.
Click the âSaveâ button.
View your map again. You should see a blue dot instead of the orange dot. If you click on the marker, it will switch back to orange. This is because there are three states for a marker:
- Default style
What you see when the map loads
- Select style
What you see when you click on a marker
- Temporary style
What you see when adding a new marker to a map
To change the Select style for this map, edit the âDrupal user groupsâ Map Configuration again at admin/structure/openlayers/maps/user_groups/edit and go back to the âLayers & Stylesâ tab. At the very bottom of the page is the âSelect styleâ drop-down. Change this to âBlue dots.â You could also create a new Style and use it here instead.
You have now used the Geofield, OpenLayers, and Views modules to create a map that displays Drupal user groups around the world. The Style of the points of the map has been customized to be more appropriate than the default colors. The configuration of fields has been tidied up so that the pop ups do not fall off the edge of the map.
We have already explored some behaviors: in OpenLayers Maps four Behaviors were chosen while setting up the Map Configuration. Behaviors in OpenLayers are map interactions such as pop ups, zoom controls, editing, and viewing fullscreen. They can be added via the user interface in Drupal and can be extended by other modules.
Note
Behaviors are a concept for how to use JavaScript in Drupal that has been best practice since Drupal 6. More details can be found on the JavaScript handbook page.
The OpenLayers Behaviors are all described on the Map Configuration page. Edit the User groups map that was created earlier at admin/structure/openlayers/maps/user_groups/edit and click on the âBehaviorsâ tab. There are lots of really useful Behaviors that come with the OpenLayers module, too many to describe here. Explore all the different Behaviors on your map and see how they work. Some of the most useful ones include:
- Tooltip
This can be used to display the title of a node when someone moves their mouse over a marker on a map.
- Fullscreen
This provides a button that expands the map to the full size of the userâs browser.
- Layer Switcher
Using Views, you can create several layers that show different but related information. When configuring the map, you can enable several such data layers, and several base layers (e.g., a Bing street map and a Google Satellite map). All of these layers will be controlled by a layer-switching widget, and users can turn them on and off.
- Cluster
See Browser Capabilities for a description and rationale for clustering. OpenLayers comes with its own JavaScript clustering script. The OpenLayers examples site provides a good demonstration of how to configure this Behavior.
- Geolocate
The latest version of the OpenLayers library takes advantage of HTML5 geolocation, as supported by most modern browsers, especially on smartphones and tablets. Users are prompted to allow the web page to access their location; then the map is updated to center on that location. A demonstration is on the OpenLayers examples site. This Behavior was added in version 2.11 of OpenLayers, so if you see the warning, âDependency not found: OpenLayers.Control.Geolocate,â this is because you are using an older version of the OpenLayers JavaScript library. That can be changed at admin/structure/openlayers.
Creating custom Behaviors is covered in Chapter 5.
On the OpenLayers configuration page at admin/structure/openlayers you may have noticed a setting for where the OpenLayers.js file is located. By default the OpenLayers module will use a JavaScript file hosted on openlayers.org. This works, but in most cases it is better to host the file yourself both for speed and reliability.
Download the latest stable release of the OpenLayers JavaScript library from openlayers.org. Alternatively, you can check out the code from the OpenLayers subversion repository.
Extract the .zip or .tar.gz file to your Drupal site, typically to a libraries directory inside the siteâs folder.
Update the OpenLayers configuration in your website at admin/structure/openlayers with the new location of the OpenLayers JavaScript file:
sites/all/libraries/OpenLayers-2.10/OpenLayers.js
.
While doing the steps above, you may have noticed that the OpenLayers JavaScript library is huge, and the OpenLayers.js file that is loaded to display a map is almost 1 MB. Once you have finished building all of your maps for a site, you can recompile this file to exclude all the Behaviors that are not needed. The library that you downloaded from http://openlayers.org/ contains a Python script and instructions inside the build directory. Further instructions are in the OpenLayers module in docs/CUSTOMIZATION.txt.
In OpenLayers layers a data layer was created using the Views module. An alternative is to use a static KML file to create the data layer. KML was introduced in Data Types. Using a KML file to generate the data layer will usually be faster than using the Views module because the spatial data does not need to be queried from the database.
Find a KML file that you would like to display on your map; for example the USGS list of the worldâs largest earthquakes. Download this file and add it to your site. In this example, weâve put it inside a custom module called âmappingdrupalexercises.â Because this file will be loaded through JavaScript, most web browsers will block the file if it is not on the same website as the map that you are creating.
From the OpenLayers moduleâs layers configuration page, add a new layer at admin/structure/openlayers/layers/add.
Click on KML in the list of layer types.
Enter the path of the KML file as the URL:
sites/all/modules/custom/mappingdrupalexercises/LargestWorldEarthquakes.kml
Enter an ID for this layer (for example,
usgs_earthquakes
).Enter a title and description, then save your new KML layer. It should show up on the list of layers at admin/structure/openlayers/layers.
Follow the instructions in OpenLayers Maps to create a new Map Configuration, choosing your earthquake layer in the âLayers & Stylesâ tab.
Follow the instructions in Using Views to display an OpenLayers map to display the map, choosing the Map Configuration that you just created.
You should end up with a map that looks something like Figure 4-9.
Get Mapping with Drupal now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.