图层控件的默认项

时间:2018-12-21 10:13:10

标签: javascript leaflet

我正在尝试将{Leaflet Layers Control}与基础层一起使用,如docs's example ...它不起作用

真实案例:

var bing_options = {
    bingMapsKey: BING_KEY,
    attribution: attribMapBase+' BING',
    culture: 'pt'
};
var 
  lay_mapbox = L.tileLayer(MAPBOX_URL+MAPBOX_KEY, {
    attribution: attribMapBase+' MapBOX',
    id: 'mapbox.streets'
  }),
  lay_bing = L.tileLayer.bing(bing_options)
;

var mymap = L.map('mapid', {
    center: [-23.56149,-46.655953],
    zoom: 20,
    layers: [lay_mapbox, lay_bing]
});
L.control.layers({
    "Standard": lay_mapbox,
    "BING": lay_bing
}).addTo(mymap);
lay_mapbox.addTo(mymap); //  set as default... NOT WORKING!

请查看最后一条命令的使用,该命令不起作用。

1 个答案:

答案 0 :(得分:2)

有了您的真实案例MCVE,现在就可以了解您的问题并为您提供与实际情况相关的帮助。

因此,让我们看看所提到的docs / tutorial :(强调我的意思)

  

还要注意,当使用多个基础层时,在实例化时仅应将其中一个添加到地图中,但是在创建图层控件时,所有这些都应存在于基础层对象中。

现在让我们看看有关layers地图实例化选项的文档:

  

最初将添加到地图的图层数组

因此,当您这样做时:

var mymap = L.map('mapid', {
  center: [-23.56149,-46.655953],
  zoom: 20,
  layers: [lay_mapbox, lay_bing] // Offending line
});

...您实际上是在地图上添加多个基本图层。由于它们在地图上已经 ,因此lay_mapbox.addTo(mymap)不会改变任何内容。

只需一开始就不添加所有内容,那么您可以有选择地选择在启动时应该可见的内容:

var
  lay_mapbox = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }),
  lay_bing = L.tileLayer('https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  });

var mymap = L.map('mapid', {
  center: [-23.56149, -46.655953],
  zoom: 20,
  // layers: [lay_mapbox, lay_bing] // Offending line
});
L.control.layers({
  "Standard": lay_mapbox,
  "BING": lay_bing
}, null, {
  collapsed: false
}).addTo(mymap);
lay_mapbox.addTo(mymap); //  set as default
html,
body,
#mapid {
  margin: 0;
  height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet-src.js" integrity="sha512-+ZaXMZ7sjFMiCigvm8WjllFy6g3aou3+GZngAtugLzrmPFKFK7yjSri0XnElvCTu/PrifAYQuxZTybAEkA8VOA==" crossorigin=""></script>

<div id="mapid"></div>

现在可能误导您的是,在上述教程中,该示例使用地图layers选项最初添加了1个基本层和1个覆盖层:

var map = L.map('map', {
  center: [39.73, -104.99],
  zoom: 10,
  layers: [grayscale, cities] // 1 base layer, 1 overlay
});

...而“图层控制”提供了2个基本图层,其中1个与上述最初添加的图层相同:

var baseMaps = {
  "Grayscale": grayscale, // Initially added to the map
  "Streets": streets // Left alone
};

var overlayMaps = {
  "Cities": cities // Initially added to the map
};

L.control.layers(baseMaps, overlayMaps).addTo(map);