我似乎无法使用 javascript 来完成这项工作。我正在尝试根据选中的复选框更新 map 上的某些图层。 这是我的代码,也是我到目前为止所尝试的。
html:
<div class="option-layer">
<input type="checkbox" value="layer1" name="Administratoret">
<input type="checkbox" value="layer11" name="njesite_adm.kml">
<input type="checkbox" value="raster" name="njesite_adm.kml">
</div>
js:
var projection = ol.proj.get('EPSG:4326');
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var layer1 = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'http://localhost/maptest/test.kml',
format: new ol.format.KML()
})
});
var layer11 = new ol.layer.VectorTile({
source: new ol.source.VectorTile({
url: 'http://localhost/maptest/test.kml',
format: new ol.format.KML({
extractStyles: false
}),
}),
opacity: 2,
});
//**the code to get value from checkbox**
var filter_options=[raster];
$('input:checkbox').click(function()
{
var name=$(this).val().trim();
if(this.checked)
{
filter_options.push(name);
console.log('Add: ' + name);
}
else
{
var index=filter_options.indexOf(name);
if(index > -1)
{
filter_options.splice(index, 1);
console.log('Remove: ' + name + ' at index: ' + index);
}
}
$('#result').html(filter_options.join('; '));
console.log(filter_options);
});
var map = new ol.Map({
layers : [raster, layer1, layer11] //this works
layers: filter_options, //this doesnt work, the map wont shoq the layers
target: document.getElementById('map'),
view: new ol.View({
center: [ 29.8187, 32.3275],
projection: projection,
zoom: 10,
})
});
我的方向正确吗?任何帮助将不胜感激。
最佳答案
当您将filter_options数组添加到 map 时,它只有一层。您正在尝试在将filter_options 数组添加到 map 后添加/删除图层。您的图层实际上并未添加到 map 中。
首先加载所有图层:
layers : [raster, layer1, layer11] //this works for you already
然后在复选框更改事件上,处理图层可见性:
layer1.setVisible(true) or
layer1.setvisible(false)
关于javascript - 单击复选框后更新 javascript 值和 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49196271/