The code snippet below creates a map variable locally inside an init() function. I am getting errors such as this.map.getLayers and map.getLayers is not a function or cannot read property getLayers of undefined, depending on how I call the function updateFliter()
If I remove the var in front of map, js creates a global variable, and updateFilter() works.
How can I call updateFliter() without creating map as a global variable?
FYI, updateFilter() is implementing a CQL filter on the geoserver layers.
function init() {
var option1 = document.createElement("option");
var option2 = document.createElement("option");
option1.text = "layer1";
option2.text = "layer2";
document.getElementById("dropdown").add(option1);
document.getElementById("dropdown").add(option2);
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
name: 'OpenStreetMap'
}),
new ol.layer.Tile({
source: new ol.source.TileWMS({
url: '../../geoserver/foo/wms',
params: {'VERSION': '1.1.1',
tiled: true,
LAYERS: 'foo:layer1',
tilesOrigin: -181.800003051758 + "," + -66.7399978637695
}
}), name: 'layer1'
}),
new ol.layer.Tile({
source: new ol.source.TileWMS({
url: '../../geoserver/foo/wms',
params: {'VERSION': '1.1.1',
tiled: true,
LAYERS: 'foo:layer2',
tilesOrigin: -181.800003051758 + "," + -66.5354995727539,
}
}), name: 'layer2'
})
]
})
var updateFunc = document.getElementById('updateFilterButton');
updateFunc.addEventListener('click', function(){updateFilter(map)});
}
//Use a CQL filter to select data to display
function updateFilter(map){
var filterParams = {'CQL_FILTER': null};
var filter = document.getElementById('CQLfilter').value;
//by default, reset all filters
if (filter.replace(/^\s\s*/, '').replace(/\s\s*$/, '') != "") {
filterParams["CQL_FILTER"] = filter;
}
this.map.getLayers().forEach(function(lyr) {
if (lyr.get('name') == dropdown.value){
lyr.getSource().updateParams(filterParams);
};
});
}