出于您的目的,您可能希望使用来自ol.source.ImageWMS 的tileLoadFunction (API doc)
为了说明,你可以看下面。 2个“秘密”是customLoader,用于身份验证以取消注释req.setRequestHeader("Authorization", "Basic " + window.btoa(user + ":" + pass));
<!DOCTYPE html>
<html>
<head>
<title>Tiled WMS</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
function customLoader(tile, src) {
var client = new XMLHttpRequest();
client.open('GET', src);
// Uncomment to pass authentication header
//req.setRequestHeader("Authorization", "Basic " + window.btoa(user + ":" + pass));
client.onload = function() {
tile.getImage().src = src;
};
client.send();
}
var layers = [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Tile({
extent: [-13884991, 2870341, -7455066, 6338219],
source: new ol.source.TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
tileLoadFunction: customLoader,
params: {'LAYERS': 'topp:states', 'TILED': true},
serverType: 'geoserver',
// Countries have transparency, so do not fade tiles:
transition: 0
})
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
center: [-10997148, 4569099],
zoom: 4
})
});
</script>
</body>
</html>
答案主要是从How to add a http header to openlayers3 requests?借来的,但由于提供的语法不起作用,所以做了一些修改。