Mapbox切换图层

时间:2014-11-18 20:03:33

标签: leaflet mapbox

我有一组23个地图框图层,我可以单独打开和关闭。我想包括一个主OFF OFF切换。我怎么能做到这一点?以下是代码:

<script type="text/javascript">
var map = L.map('map',{center: [56.5, -1], minZoom: 7, zoomControl: false, legendControl: true}).setView([56.5, -1], 7);
map.addControl(new L.Control.ZoomMin())
var baseLayer = new L.mapbox.tileLayer('inosys.k52e98ob').addTo(map);
var ui = document.getElementById('map-ui');

var overlays = [
['inosys.k8mg7jp2','Toggle All On', 1], 
['#','Toggle All Off', 1], 
['inosys.jgsk2of8','Significant Discoveries', 999999],
['inosys.gaa3x433','Wells', 999999],
['inosys.gaa3xpkf','Hydrocarbon Fields', 3],
['inosys.u0uttr1z','Field Determinations', 3],
....

1 个答案:

答案 0 :(得分:2)

在选择切换按钮时,您可以运行一个迭代所有图层的函数并将其删除,如下所示:

function toggleAllOff(){
  map.eachLayer(function (layer) {
    map.removeLayer(layer);
  });
}

您还可以将所有图层添加到单个图层组中,然后按照另一个问题here上的说明调用该组上的clearLayers

修改 下面显示了在特定情况下工作所需的代码。它有点hacky,因为该方法删除了基础层并将其重新添加。如果您不想删除基础层,可以快速检查一下。

link.onclick = function (e) {
    e.preventDefault();
    e.stopPropagation();

//Add the following
    if ($(this).text() == 'Toggle All Off') {
        map.eachLayer(function (layer) {
            map.removeLayer(layer);
        });
        map.addLayer(baseLayer);
    } else if (map.hasLayer(layer)) {

//The rest is your old code
        map.removeLayer(layer);
        map.removeLayer(gridlayer);
        map.removeControl(gridControl);
        map.removeControl(legendControl);
        this.className = '';