Я хочу создать карту листов, которая может переключаться между различными слоями карты. Это, конечно, не проблема.Листовка: смесь между двумя базовыми слоями
Но я хочу добавить ползунок, где я могу смесь между фактической maplayer и бывшего maplayer удобно сравнивать содержание этих 2-х карт:
бегунок = правый => 100% непрозрачность фактической карты
слайдера = влево => 0% непрозрачность фактической карты, что означает 100% непрозрачность бывшей карты
слайдер = средний => 50% непрозрачность фактической карты, что означает для mer в фоновом режиме также светится на 50%
Мне удалось получить смесь, которая работает в начальной ситуации после загрузки карты. Но я не могу заставить его работать после того, как я выберу другую карту из меню выбора карты. Бывший maplayer, который должен отображаться в фоновом режиме, кажется, теряется.
я вещь, что проблема заключается в том, что функция «fct_layerchange» не только называют ивент-listenier map.on когда я выбираю другую карту в пределах меню Maplayers, но и когда я добавьте прежний maplayer в фоновый режим с помощью map.addLayer (bgMap);
Я больше понятия не имею, как решить эти нежелательные «многократные» функции, поскольку я полагаюсь на событие baselayerchange при выборе новой базовой карты. И это событие снова срабатывает, когда оно находится внутри функции события. Есть ли у какого-нибудь лифлет-гуру идея, как я могу это решить? :-)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blend 2 maps</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<style>
html, body, #map {height: 100%;}
</style>
</head>
<body>
<div id="map"></div>
<script>
// 1.) BASEMAPS
var osm_mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {subdomains:'abc', maxZoom:19, noWrap:true, attribution:'<a href="http://www.openstreetmap.org">Openstreetmap</a> | <a href="http://www.openstreetmap.org/copyright/">OpenStreetMap</a>' });
var thunder_cycle = L.tileLayer('https://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png', {subdomains:'abc', maxZoom:19, noWrap:true, attribution:'<a href="http://www.thunderforest.com">Thunderforest</a> | <a href="http://www.openstreetmap.org/copyright/">OpenStreetMap</a>' });
var thunder_outdoors = L.tileLayer('https://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png', {subdomains:'abc', maxZoom:19, noWrap:true, attribution:'<a href="http://www.thunderforest.com">Thunderforest</a> | <a href="http://www.openstreetmap.org/copyright/">OpenStreetMap</a>' });
var thunder_pioneer = L.tileLayer('https://{s}.tile.thunderforest.com/pioneer/{z}/{x}/{y}.png', {subdomains:'abc', maxZoom:19, noWrap:true, attribution:'<a href="http://www.thunderforest.com">Thunderforest</a> | <a href="http://www.openstreetmap.org/copyright/">OpenStreetMap</a>' });
// 2.) OVERLAYMAPS
var heidel_bound = L.tileLayer('http://korona.geog.uni-heidelberg.de/tiles/adminb/x={x}&y={y}&z={z}', {maxNativeZoom: 18, maxZoom:19, noWrap:true, attribution:'<a href="http://korona.geog.uni-heidelberg.de/contact.html">Uni-Heidelberg</a>' });
var wmt_hiking = L.tileLayer('https://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png', {maxNativeZoom: 18, maxZoom:19, noWrap:true, attribution:'<a href="http://waymarkedtrails.org">Waymarkedtrails</a>' });
// LAYERMENU
var baseMaps = {
"OpenStreetMap Mapnik": osm_mapnik,
"Thunderforest Opencycle": thunder_cycle,
"Thunderforest Outdoors": thunder_outdoors,
"Thunderforest Pioneer": thunder_pioneer
};
var map = L.map ('map', { center: [47, 15], zoom: 11, layers: [thunder_cycle, wmt_hiking] });
var overlayMaps = {
"Hiking Routes": wmt_hiking,
"Boundaries": heidel_bound,
};
var ctr_mapLayers = L.control.layers(baseMaps, overlayMaps).addTo(map);
var fgMap = thunder_cycle;
var bgMap = thunder_pioneer;
map.addLayer(bgMap); // add initial backgroundmap-layer to map
bgMap.bringToBack(); // move backgroundmap-Layer to to the background of the map
function fct_blend() {
valBlend = document.getElementById("id_sliderBlend").value;
document.getElementById("id_valBlend").innerHTML = Number(valBlend).toFixed(1)
fgMap.setOpacity(valBlend);
}
var ctr_blend = L.control();
ctr_blend.onAdd = function (map) {
valOpacity = 1.0;
this.div = L.DomUtil.create('div');
this.div.innerHTML = '<span id="id_valBlend">1.0</span><input type="range" id="id_sliderBlend" min="0" max="1" step="0.1" value="1" style="width:100px;" oninput="fct_blend()">';
L.DomEvent.disableClickPropagation(this.div);
return this.div;
};
ctr_blend.addTo(map);
var fct_layerchange = function (e) {
bgMap = fgMap;
bgMap.setOpacity(1); // set opacity of former foregroundmap-layer which is now background-layer to 1.0;
map.addLayer(bgMap); // add former foregroundmap-layer as backgroundmap-layer to map again.
fgMap = e.layer; // update fgMap-variable with the actual foregroundmap-layer
fgMap.setOpacity(valBlend); // set opacity of the new foregroundmap-layer to the actual blend-Value.
};
map.on('baselayerchange', fct_layerchange);
</script>
</body>
</html>
Вы можете быть заинтересованы в [Leaflet.OpacityControls] плагин (https://github.com/lizardtechblog/Leaflet.OpacityControls). Это может помочь в настройке непрозрачности, но вам все равно придется выяснить, как изменить слой и контролировать непрозрачность текущего слоя. – ghybs