- Skip to main content
- Skip to "About this site"

# Geomap

Questions or comments?

## Purpose

Displays a map over which information from additional sources can be overlaid.

## Use when

- You want to display a dynamic map with data overlays
- You want to display a static map

## Working example

- English example
- French example

## How to implement

1. Add a `div` element with `class="wb-geomap"` and assign it a unique `id`.
2. Add `div` with `class="wb-geomap-map"` to the `div` created in step 1 where you want the map to be rendered.
3. Add `div` with `class="wb-geomap-layers"` to the `div` created in step 1 where you want the layer(s) listing to be rendered.

### Optional elements

- Add legend: If a map legend is required add `div` with `class="wb-geomap-legend"` to the `div` created in step 1 where you want it to be rendered.
- Add widgets: Widgets (e.g. position, scaleline, etc.) are configured using classes on the plugin element created in step 1.

Note: If you are implementing the working example on your development environment you may need to add the necessary support for the mime-types required by the various formats demonstrated (e.g. ".kml" "application/vnd.google-earth.kml+xml") to your web server.

### Example implementation markup

    <-- Add plugin with optional position widget -->
    <div id="mygeomap" class="wb-geomap position">
    	<div class="row">
    		<div class="col-md-9">
    			<div class="wb-geomap-map"></div>
    		</div>
    		<-- Add optional map legend -->
    		<div class="wb-geomap-legend col-md-3">
    			<h2>Legend</h2>
    			<-- Geomap will insert legend here -->
    		</div>
    		<div class="row">
    			<-- Add placeholder for overlays -->
    			<div class="wb-geomap-layers col-md-12"></div>
    		</div>
    	</div>
    </div>

### Plugin configuration options

Geomap can be configured in four ways:

- Using the `data-wb-geomap` attribute on the plugin element
- Using `window[ "wb-geomap" ]`
- Using a configuration file
- Using CSS classes on the plugin element

Note: all plugin configuration parameters are optional.

#### Configuration using `data-wb-geomap` attribute on plugin element

Use the `data-wb-geomap` attribute to configure the display of map features from inline HTML tables or from a local/remote data source.

Parameter | Value | Description
--- | --- | ---
`tables` | Array | An array if inline HTML table id's from which map features are to be loaded and their configurations.
`layersFile` | String | Path to local or remote JavaScript configuration file that lists feature layers that are to be added to the map.

#### Configuration using a configuration file

An optional configuration file can be used to specify alternative basemaps and external feature overlays. The configuration file is referenced in the `data-wet-beow` attribute of the plugin element by setting the `layersFile` property to the file path.

Parameter | Value | Description
--- | --- | ---
`basemap` | JavaScript Object | A base map configuration that includes map settings (e.g., maximum and default extents, units, projection, etc.) and connection specifics for a WMS base map service.
`overlays` | Array | A list of layers to be added to the map with associated configurations.

##### Example configuration file reference

    <div id="mygeomap" class="wb-geomap" data-wb-geomap='{ "layersFile": "data/config-en.min.js" }'> ... </div>

#### Configuration using CSS classes

Configure which features and widgets you want added to your map by using CSS classes.

Class | Description
--- | ---
`aoi` | If present, an area-of-interest (AOI) widget is added to the map. The AOI widget allows user to draw a bounding box extent to the map where the coordinates are made available in a hidden field that developers can attach a listener to. Useful for search and discovery applications. Geomap will write the AOI extent to two hidden fields, one in the maps projection and the other in longitude/latitude.
    <input type="hidden" id="geomap-aoi-extent-1" value="553816,1951915,2188045,3573694">
    <input type="hidden" id="geomap-aoi-extent-lonlat-1" value="-73, 65, -39, 76">
Access the values of the hidden fields by attaching a listener to the "change" event.
    wb.doc.on( "geomap.ready", function( event, maps ) {

      var myMap = maps.mygeomap,
        $aoiExtent = $( "#geomap-aoi-extent-" + myMap.uniqueId ),
        $aoiExtentLonLat = $( "#geomap-aoi-extent-lonlat-" + myMap.uniqueId ), bbox, bboxProj;

      $aoiExtent.on( "change", function() {
        bbox = $( this ).val() ); // in map projection
        // do something
      } );

      $aoiExtentLonLat.on("change", function() {
        bboxLonLat = $( this ).val() ); // in longitude/latitude
        // do something
      } );

    });
The AOI widget can be configured (v4.0.11+) so that it is enabled by default by setting the `toggle` property to false using the `data-wb-geomap` attribute on plugin element.
    <div id="mygeomap" class="wb-geomap" data-wb-geomap='{ ... "aoi": { "toggle": false } ... }'> ... </div>
The AOI widget can be configured(v4.0.11+) with an initial extent by setting the `extent` property using the `data-wb-geomap` attribute on plugin element.
    <div id="mygeomap" class="wb-geomap" data-wb-geomap='{ ... "aoi": { "toggle": false, , "extent": "-57, 46, -51, 50" } ... }'> ... </div>
`geocoder` | If present, the geocoder widget will be added to the map. The geocoder widget allows users to search for postal codes, street addresses, placenames and NTS sheet numbers. The map is panned and zoomed to the location selected.
`geolocation` | If present, the geolocation widget will be added to the map. When activated, the map will be panned and zoomed to the location of the client. Note that users must allow their client to share its location with Geomap.
`position` | If present, the mouse position widget will be shown in the lower left corner of the map.
`scaleline` | If present, the scale line widget will be shown in the lower left corner of the map.
`static` | If present, the widgets (pan, zoom, select, etc.) will not be added to the map. This is useful for scenarios where a simple map with one or more features is required to communicate some value or idea (e.g. an extent map for a data product).
`tab` | If present, a tab control will be added to the page where feature tables can be added. Note that an overlay configuration would need to specify that it is to be placed in a tab control.

Configuration class example:

    <div id="mygeomap" class="wb-geomap position scaleline"> ... </div>

### Basemap configuration options

Note: Geomap does not require a base map configuration. A default base map will be provided if none is configured.

Parameter | Required | Value | Default | Description
--- | --- | --- | --- | ---
`title` | Yes | String | '' | The title of the base layer (not displayed)
`type` | Yes | String | '' | The type of data source. Note that this must be 'wms'.
`url` | Yes | String | '' | The url of the WMS service providing the base map. For example 'http://geogratis.gc.ca/maps/CBMT'.
`layers` | No | String | '' | A comma delimited string of layer ids to be requested from the WMS service.
`format` | Yes | String | '' | The mime-type of the format to be requested of the WMS service.
`version` | Yes | String | '' | The version of the WMS service being requested.
`options` | No | Array | '' | A comma delimitated array of OpenLayers options for WMS layer types.
`mapOptions` | No | Array | '' | An array of OpenLayers map configuration options.

#### Basemap configuration example

    basemap : {
        title: 'CBMT',
        type: 'wms',
        url: 'http://geogratis.gc.ca/maps/CBMT',
        layers: 'CBMT',
        format: 'image/png',
        version: '1.1.1',
        options: { singleTile: true, ratio: 1.0, projection: 'EPSG:3978', fractionalZoom: true },
        mapOptions: {
            maxExtent: '-3000000.0, -800000.0, 4000000.0, 3900000.0',
            maxResolution: 'auto',
            projection: 'EPSG:3978',
            restrictedExtent: '-3000000.0, -800000.0, 4000000.0, 3900000.0',
            units: 'm',
            displayProjection: 'EPSG:4269',
            numZoomLevels: 12
        }
    }

### Adding feature overlays

Feature overlays can be generated from page markup (i.e. HTML tables) or from external sources (e.g. feeds, KML, web API's).

#### Adding features from an HTML table in the page

Geomap can create features from HTML markup in the page.

##### Steps:

1. Add a unique `id` to each table (e.g. "myTable") and ensure that each table row (i.e. `tr`) element has the required attributes. See below for configuration.
2. Add the unique `id` created in step 1 to a `tables` array in the `data-wb-geomap` attribute of the plugin element.

       <div id="mygeomap" class="wb-geomap" data-wb-geomap='{ "tables": [ { "id": "myTable", "style": { ... } } ] }'> ... </div>

##### Inline HTML table configuration

Geomap requires a `data-geometry` attribute with feature geometry encoded in Well Known Text (WKT) or as a bounding box extent with lower left and upper right coordinate pairs, and a `data-type` attribute that specifies the encoding as either `wkt` or `bbox`.

##### WKT examples

    <tr data-geometry="POINT (-114.05879, 51.04668)" data-type="wkt"> ... </tr>

    <tr data-geometry="LINESTRING (30 10, 10 30, 40 40)" data-type="wkt"> ... </tr>

    <tr data-geometry="POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))" data-type="wkt"> ... </tr>

Other geometry types are supported. See Well-known text for more examples.

##### Bbox example

    <tr data-geometry="-136, 61, -118, 70" data-type="bbox"> ... </tr>

##### Inline HTML table configuration example

    <table id="cities" aria-label="Cities">
    	<caption>Major cities in Canada.</caption>
    	<thead>
    		<tr>
    			<th>Rank</th>
    			<th>Census subdivision</th>
    			<th>Population 2011</th>
    		</tr>
    	</thead>
    	<tbody>
    		<tr data-geometry="POINT (-79.3847, 43.6476)" data-type="wkt">
    			<td>1</td>
    			<td class="select">
    				<a href="../Toronto" title="Toronto">Toronto</a>
    			</td>
    			<td>2615060</td>
    		</tr>
    		<tr data-geometry="POINT (-73.56123, 45.52927)" data-type="wkt">
    			<td>2</td>
    			<td class="select">
    				<a href="../Montreal" title="Montreal">Montreal</a>
    			</td>
    			<td>1649519</td>
    		</tr>
    		...
    	</tbody>
    </table>

Note that attribute names for features rendered from an inline HTML table are taken from the table header. In the preceding example the table header would result in attributes named "Rank", "Census subdivision", and "Population 2011".

#### Adding features from external data sources via a configuration file

##### Steps:

1. Create a Javascript configuration file and save it to a web accessible directory (e.g. "data/config-en.min.js").
2. Add an `overlays` array to the `wet_boew_geomap` variable in the configuration file.

       // Configuration file ("data/config-en.min.js")
       var wet_boew_geomap = {
           overlays : [
               {
                   title: 'KML Demo EN',
                   caption: 'This is a sample KML file loaded locally by Geomap.',
               type: 'kml',
               url: 'data/sample.kml',
               visible: true
               },
               { ... }
           ]
       };

3. Reference the configuration file in the `data-wb-geomap` attribute of the plugin element by setting the `layersFile` property to the file path.

       <div id="mygeomap" class="wb-geomap" data-wb-geomap='{ "layersFile": "data/config-en.min.js" }'> ... </div>

#### Feature overlay configuration options

Parameter | Required | Value | Default | Description
--- | --- | --- | --- | ---
`attributes` | No | Array | '' | An array of feature attributes to be displayed in the table with their aliases. For example: `attributes: { location_desc: 'Location', longitude: 'Latitude', latitude: 'Longitude', updated_at: 'Last updated' }`.
`caption` | Yes | String | '' | The description of the overlay to be displayed in the table caption of the page.
`datatable` | No | Boolean | '' | If true the feature table will be enhanced using the Tables plugin which provides sorting, paging and searching functions.
`params` | No | Array | '' | An array of parameters to send to the datasource/service. For example: `params: { 'alt': 'json', 'q': 'alluvial' }`. These will be added to the request URI.
`popups` | No | Boolean | '' | If true popups for features will be enabled. Note that the "`popupsInfo`" parameter allows for customization of the popup and its content.
`popupsInfo` | No | String | '' | Allows for customization of popup content. Has several configuration options: "`height`" in pixels, "`width`" in pixels, "`close`" which if set to `true` will result in a close button being rendered, and "content" which can contain any HTML markup desired.
`root` | No | Boolean | '' | Name of the root element that contains the array of objects that contain the features to be rendered.
`style` | No | Array | '' | An OpenLayers style object. Unique and rule based styles are supported. Note that Geomap will assign a default style if none is provided. However, the default color combination may not have the contrast required to meet WCAG guidelines. Therefore, a style should be configured before going into production.
`tab` | Yes | Boolean | '' | If true, the feature table will be rendered in a tab control.
`title` | Yes | String | '' | The title of the overlay to be displayed in the legend, tabs (if configured) and/or the page.
`type` | Yes | String | '' | The type of datasource for the overlay. Must be one of: atom, kml, json, geojson, georss.
`url` | Yes | String | '' | The url of the data source. For example 'http://geogratis.gc.ca/api/en/nrcan-rncan/ess-sst'.
`visible` | No | Boolean | `false` | Controls the visibility of the overlay. Note that without a legend the visibility of an overlay can't be changed.
`zoom` | No | Boolean | '' | If true a "Zoom to feature" button will be added to each row in the feature table.

#### Feature overylay configuration example

    {
      attributes: {
        location_desc: 'Location',
        longitude: 'Latitude',
        latitude: 'Longitude',
        updated_at: 'Last updated'
      },
      caption: 'Traffic cameras in the city of Ottawa.',
      datatable: true,
      params: {
        'format': 'GeoJSON',
        'q': 'SELECT * FROM traffic_cameras LIMIT 25'
      },
      style: { ... },
      tab: true,
      title: 'Traffic Cameras',
      type: 'geojson',
      url: 'http://stephenott.cartodb.com/api/v2/sql',
    	visible: true,
      zoom:  true
    }

#### Style configuration options

##### Basic style example - all features using the same style

    style: {
      'strokeColor': '#ff0000',
      'fillColor': '#ff0000',
      'fillOpacity': '0.4'
    }

##### Style example with override for selected feature

    style: {
      type: 'symbol',
      init: { 'pointRadius': '15', 'externalGraphic': '../icon.png' },
      select: { 'pointRadius': '15', 'externalGraphic': '../icon_selected.png' }
    }

##### Rule based example - features are styled according to specified rules

    style: {
      type: 'rule',
      rule: [
        {
          field: 'Population2011',
          value: [ 1000000 ],
          filter: 'LESS_THAN',
          init: { strokeColor: '#0083f5', fillColor: '#57a8f0', pointRadius: '6' }
        },
        {
          field: 'Population2011',
          value: [ 1000000, 2000000 ],
          filter: 'BETWEEN',
          init: { strokeColor: '#F90', fillColor: '#F90', pointRadius: '8' }
        },
        {
          field: 'Population2011',
          value: [ 2000000 ],
          filter: 'GREATER_THAN',
          init: { strokeColor: '#F00', fillColor: '#F00', pointRadius: '10' }
         }
      ]
    }

##### Unique style example - features have unique style based on an attribute

    style: {
      type: 'unique',
      field: 'Location',
      init: {
        // using the value from the 'Location' attribute, create a unique style for each feature
        'Bayshore & Richmond': { 'fillColor': '#000099' },
        'Baseline & Greenbank': { 'fillColor': '#009900' }
      },
      // specify a style for selected features (optional). Note here we are adding a label when
      // a feature is selected.
      select: { 'fillColor': '#990000', 'label': '${ Location }' }
    }

#### Popup Configuration Options

To add popup with no customization simply add `"popups": true`. By default popups contain the same information as that is displayed in the corresponding table row for the feature.

If you need more control over your popups, you can customize them by passing a configuration through the "`popupsInfo`" parameter. The "`popupsInfo`" "`content`" parameter can contain any HTML markup you desire. Where feature attributes are required to be rendered simply add the attribute name with an underscore at the beginning. For example, if you have a feature attribute named "Census subdivision" you would reference it in your popup content as "_Census subdivision".

The following example shows all available configuration options:

    ...
    "popups": true,
    "popupsInfo": {
      "id": "citiesPopup",
      "height": 200,
      "width": 300,
      "close": true,
      "content": "<h4>_Census subdivision</h4><p>_Population 2011</p>"
    },
    ...

### Adding WMS Overlays (v4.0.11+)

Geomap will not generate an HTML table of map features for WMS overlays. Consequently WMS overlays should only be used when feature based alternatives are not available as accessibility is severly compromised.

    {
      title: "WMS Demo",
      caption: "This is a sample WMS service loaded by Geomap.",
      type: "wms",
      url: "http://geo.weather.gc.ca/geomet/?Lang=E",
      visible: false,
      version: "1.1.1",
      format: "image/png",
      layers: "GDPS.ETA_PR",
      transparent: true,
      options: {
      opacity: 0.5
      }
    }

#### WMS Legend

Geomap supports both graphic and HTML legends. WMS overlay legends can be configured in the `options` property of the layer configuration.

##### Graphic legend example:

    ...
    options: {
      ...
      legendGraphicUrl: "http://geo.weather.gc.ca/geomet/?Lang=E&LAYERS=GDPS.ETA_PR&VERSION=1.1.1&FORMAT=image%2Fpng&SERVICE=WMS&REQUEST=GetLegendGraphic&STYLE=PRECIPMM"
       ...
    }
    ...

##### HTML legend example:

    ...
    options: {
      ...
      legendHTML: "GeoMet Precipitation (mm)" +
        "<ul class='list-unstyled'>" +
        "<li><span style='background-color:#800000;display:inline-block;height:20px;width:20px'/> <small>100.0</small></li>" +
        "<li><span style='background-color:#FF0000;display:inline-block;height:20px;width:20px'/> <small>50.0</small></li>" +
        "<li><span style='background-color:#FFA500;display:inline-block;height:20px;width:20px'/> <small>20.0</small></li>" +
        "<li><span style='background-color:#E5E500;display:inline-block;height:20px;width:20px'/> <small>10.0</small></li>" +
        "</ul>"
      ...
    }
    ...

### Advanced Configuration

Geomap provides developers with a hook to access the OpenLayers Map object. This can be useful if you have specific functionality that Geomap does not support out of the box. Geomap fires an event when it has loaded that you can attach a listener to.

Once Geomap has loaded, the OpenLayers Map object can be accessed as follows:

#### Pre v4.0.5

    // return an array of OpenLayers maps in the page
    wb.doc.on( "geomap.ready", function( event, maps ) {
      var myMap = maps.mygeomap; // return map with specfic id
      // do something
    });

Note that the `id` (e.g. "mygeomap") of the `div` that contains the instance of Geomap you are accessing is used as the key in the maps array.

For example if you want Geomap to zoom the map (e.g. "mygeomap") to the extent of a specified layer (e.g. "#bbox") once the document is loaded simply add the following to your markup:

    <script>
      wb.doc.on( "geomap.ready", function( event, maps ) {
        var myMap = maps.mygeomap;
        myMap.zoomToExtent( myMap.getLayer( "#bbox" ).getDataExtent(), true );
      });
    </script>

#### v4.0.5+

    // get the map object with id "mygeomap"
    $document.on( "wb-ready.wb-geomap", "#mygeomap", function( event, map ) {
      var myMap = map; // return OpenLayers map object
      // do something
    });

Note the `id` (e.g. "mygeomap") of the `div` that contains the instance of Geomap you are accessing.

For example if you want Geomap to zoom the map (e.g. "mygeomap") to the extent of a specified layer (e.g. "#bbox") once the document is loaded simply add the following to your markup:

    <script>
      $document.on( "wb-ready.wb-geomap", "#mygeomap", function( event, map ) {
        // Get the map to use in zoomFeature function
        var myMap = map;
        myMap.zoomToExtent( myMap.getLayer( "#bbox" ).getDataExtent(), true );
      });
    </script>

## Events

Event | Trigger | What it does
--- | --- | ---
`wb-init.wb-geomap` | Triggered manually (e.g., `$( ".wb-geomap" ).trigger( "wb-init.wb-geomap" );`). | Used to manually initialize the Geomap plugin. Note: The Geomap plugin will be initialized automatically unless the required markup is added after the page has already loaded.
`wb-ready.wb-geomap` (v4.0.5+) | Triggered automatically after Geomap initializes. | Used to identify the element where Geomap has initialized (target of the event) and to pass along the map object.
    $( document ).on( "wb-ready.wb-geomap", ".wb-geomap", function( event, map ) {
    });
    $( ".wb-geomap" ).on( "wb-ready.wb-geomap", function( event, map ) {
    });
`wb-updated.wb-geomap` (v4.0.5+) | Triggered automatically after Geomap updates (e.g., change in zoom). | Used to identify the element where Geomap has been updated (target of the event) and to pass along the map object.
    $( document ).on( "wb-updated.wb-geomap", ".wb-geomap", function( event, map ) {
    });
    $( ".wb-geomap" ).on( "wb-updated.wb-geomap", function( event, map ) {
    });
`wb-ready.wb` (v4.0.5+) | Triggered automatically when WET has finished loading and executing. | Used to identify when all WET plugins and polyfills have finished loading and executing.
    $( document ).on( "wb-ready.wb", function( event ) {
    });

## Source code

Geomap plugin source code on GitHub

Date modified:
  2014-10-28