I'm new to this world of web mapping and stuck in this problem. I want to access the ChartWorld WMS service using OpenLayers. I can access it from a specific IP address using this javaScript code and everything works fine:
const ENCIPLayer = new ol.layer.Image({
source: new ol.source.ImageWMS({
ratio: 1,
params: {LAYERS: 'ENC', CSBOOL: '2183', CSVALUE: '10,5,20,10,1,2,1,4000000,100000,200000,1'},
url: 'https://wms.chartworld.com/?'
})
});
But I don't know how to access the service using username/password and basic http authentication. The address for this method is
https://wms-eval.chartworld.com
I searched a lot, but didn't find anything working !
You will need a custom load function similar to the one documented in https://openlayers.org/en/latest/apidoc/module-ol_Tile.html#~LoadFunction (tile source have a tileLoadFunction
, image sources have a imageLoadFunction
) and add a basic authentication header. To conserve memory object urls should be revoked after use.
source: new ol.source.ImageWMS({
ratio: 1,
params: {LAYERS: 'ENC', CSBOOL: '2183', CSVALUE: '10,5,20,10,1,2,1,4000000,100000,200000,1'},
url: 'https://wms.chartworld.com/?',
imageLoadFunction: function (image, src) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.open('GET', src);
xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(username + ':' + password));
xhr.onload = function() {
const url = URL.createObjectURL(xhr.response);
const img = image.getImage();
img.addEventListener('load', function() {
URL.revokeObjectURL(url);
});
img.src = url;
};
xhr.send();
}
})