Switch Tile on and off

Map

When using the maps, content is loaded from third-party servers. If you agree to this, a cookie will be set and this notice will be hidden. If not, no maps will be displayed.

Shortcode

[leaflet-map mapid=OSM]
[tile_onoff]

Code

Use e.g. WPCode and configure this as a PHP snippet in Frontend only.

<?php
function leafext_tile_onoff_script(){
  $text = '
  <script>
  window.WPLeafletMapPlugin = window.WPLeafletMapPlugin || [];
  window.WPLeafletMapPlugin.push(function () {
    let map = window.WPLeafletMapPlugin.getCurrentMap();
    let tiles = [];
    let opacity = [];
    map.eachLayer(function(layer) {
      if( layer instanceof L.TileLayer ) {
        // console.log(layer);
        tiles[layer.options.id] = layer;
        opacity[layer.options.id] = layer;
      }
    });
    // If you want switch on off
    L.control.layers(null, tiles).addTo(map);
    // If you want to control opacity
    L.control.opacity(opacity,{
      collapsed:true
    }).addTo(map);
  });
  </script>';
  return "\n".$text."\n";
}
function leafext_tile_onoff_function( ){
  leafext_enqueue_opacity();
  return leafext_tile_onoff_script();
}
add_shortcode('tile_onoff','leafext_tile_onoff_function');
Nofollow!