Multiple layers in Leaflet with custom module

Last updated on
29 November 2023

This documentation needs review. See "Help improve this page" in the sidebar.

See the example in the leaflet.api.php file, where you should implement the hook_leaflet_map_info() function.

  1. Add the code below to a custom module and clear cache
  2. Enable "Multilayers" in your View under Format > Leaflet Map > Settings > Leaflet Map Tiles Layer
  3. There should now be a multi-layer control in the top right corner of your map

See also Layer Groups and Layers Control.

/**
 * Implements hook_leaflet_map_info().
 */
function custom_module_leaflet_map_info() {

  $map_info['multilayers'] = [
    'label' => 'Multilayers',
    'description' => t('Multilayers'),
    'settings' => [
      'dragging' => TRUE,
      'touchZoom' => TRUE,
      'scrollWheelZoom' => TRUE,
      'doubleClickZoom' => TRUE,
      'zoomControl' => TRUE,
      'attributionControl' => TRUE,
      'trackResize' => TRUE,
      'fadeAnimation' => TRUE,
      'zoomAnimation' => TRUE,
      'closePopupOnClick' => TRUE,
      'minZoom' => 2,
      'maxZoom' => 20,
      'zoom' => 15,
      'layerControl' => TRUE,
      'layerControlOptions' => [
        'position' => 'topright',
      ],
    ],
    'layers' => [
      'OpenTopoMap' => [
        'urlTemplate' => '//{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
        'options' => [
          "minZoom" => 0,
          "maxZoom" => 18,
          "attribution" => 'Kartendaten: © <a href="https://openstreetmap.org/copyright">OpenStreetMap</a>-Mitwirkende, SRTM | Kartendarstellung: © <a href="http://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
        ],
      ],
      'Stamen Watercolor' => [
        'urlTemplate' => '//tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg',
          'options' => [
          "minZoom" => 0,
          "maxZoom" => 18,
          "attribution" => '&copy; <a href="https://stadiamaps.com/" target="_blank">Stadia Maps</a> <a href="https://stamen.com/" target="_blank">&copy; Stamen Design</a> &copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a> &copy; <a href="https://www.openstreetmap.org/about" target="_blank">OpenStreetMap</a> contributors',
        ],
      ],
      'Google Roads' => [
        'type' => 'google',
        'urlTemplate' => '//mt{s}.googleapis.com/vt?x={x}&y={y}&z={z}',
        'options' => [
          'attribution' => 'Map data &copy; <a href="https://googlemaps.com">Google</a>',
          'detectRetina' => FALSE,
          'subdomains' => [0, 1, 2, 3],
        ],
      ],

    ],
  ];

  return $map_info;

}

Help improve this page

Page status: Needs review

You can: