問題描述
有人可以幫我弄清楚如何在將傳單添加到地圖時默認設置OFF嗎?例如,在地圖上設置CITIES圖層OFF,如下面的代碼所示.關鍵是默認情況下只有 STATES 層 ON 和 CITIES OFF.
Could someone help me to figure out how to set a leaflet overlay OFF by default when adding it to the map, please? For instance, setting the CITIES layer OFF on the map, as shown in the code below. The point is to have only the STATES layer ON and the CITIES OFF by default.
var baseMaps = {
"Grayscale": grayscale,
"Streets": streets
};
var overlayMaps = {
"Cities": cities, // Need to set OFF over the map
"States": states // Need to set ON over the map
};
L.control.layers(baseMaps, overlayMaps).addTo(map);
推薦答案
你不應該首先將它添加到地圖中.在您發布該代碼之前的某處,您初始化了城市圖層并將其添加到地圖中.否則它不會出現在地圖上.例如:
You should not add it to the map in the first place. Somewhere before that code you posted you initialize the cities layer and add it to the map. Otherwise it wouldn't be on the map. For example:
var cities = new L.GeoJSON(...);
cities.addTo(map);
//Or
var cities = new L.GeoJSON(...);
map.addLayer(cities);
現在,當您將其添加到圖層控件時,控件會自動選中它的復選框,因為它已經添加到您的地圖中.
Now when you add that to your layer control it's checkbox is automaticly checked by the control because it's already added to your map.
在注釋后添加示例以進行澄清.這是一個添加到地圖的圖層組,另一個沒有.兩者都添加到圖層控件中.在控件中只檢查添加到地圖的那個:
Example added after comment for clarification. Here is one layergroup added to the map and the other is not. Both are added to the layer control. Only the one that is added to the map is checked in the control:
var map = new L.Map('leaflet', {
center: [0, 0],
zoom: 0,
layers: [
new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
'attribution': 'Map data ? <a >OpenStreetMap</a> contributors'
})
]
});
// LAYERGROUP WITH ADD TO MAP
var layerGroup1 = new L.LayerGroup([
new L.Marker([25, 25])
]).addTo(map);
// LAYERGROUP WITHOUT ADD TO MAP
var layerGroup2 = new L.LayerGroup([
new L.Marker([-25, -25])
]);
var layerControl = new L.Control.Layers(null, {
'Group 1': layerGroup1,
'Group 2': layerGroup2
}).addTo(map);
body {
margin: 0;
}
html, body, #leaflet {
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<title>Leaflet 1.0.3</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" />
</head>
<body>
<div id="leaflet"></div>
<script type="application/javascript" src="http://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
</body>
</html>
這篇關于在圖層控件中設置 Leaflet Overlay Off的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!