问题
I am displaying a leaflet base map. I am using an HTML5 slider to set the opacity to a layergroup but it is not working.
I was wondering what I'm doing wrong.
Thanks in advance!
<h3>TF.Landscape</h3>
<br><input type="button" value=" + " onclick="BaseMapAsLayerGroup('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png')">
<br><input id="slide" type="range" min="0" max="1" step="0.1" value="0" onchange="updateOpacity(this.value)">
<hr>
<div id="map" style="width: 800px; height: 600px"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"> </script>
<script>
var map;
var capa;
function BaseMapAsLayerGroup(url){
if(!map) {
map = L.map('map').setView([-41.2858, 174.78682], 14);
}
capa = new L.LayerGroup();
L.tileLayer(url, {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>',
maxZoom: 18
}).addTo(capa);
map.addLayer(capa);
}
function updateOpacity(value) {
capa.opacity(value);
}
</script>
回答1:
I think you want to set the opacity of the layer (capa
) and not the map. That variable would need to be scoped differently for this to work. A quick way to do this would be to declare capa
just under the var map
at the top of the script.
function updateOpacity(value) {
capa.opacity(value);
}
EDIT:
I think this fiddle illustrates what you are trying to do. There's a couple things that were missing/wrong with the code as it was in the original post including omitting a link to the CSS that is needed for the leaflet library.
Single Layer controlled by its own slider
EDIT:
Two Layers, each controlled by their own slider
回答2:
One other way to change the opacity could be to use the setstyle
function. Hence for your case, try this
function updateOpacity(value) {
capa.setStyle({opacity:value});
}
来源:https://stackoverflow.com/questions/31254277/leaflet-js-set-opacity-to-layergroup-with-slider