[英]How to use XMLHttpRequest with Open Layers
我需要使用 Open Layers(和純 Javascript)從多個 WebMapServer(我公司的)獲取圖像。 基本上它有效。 問題是某些服務器需要 HTTP 基本身份驗證。 OL 文檔和相關的 SO 問題說這應該通過 imageLoadFunction 中的 XMLHttpRequest 來完成:
https://openlayers.org/en/latest/apidoc/module-ol_Image.html
如何將基本身份驗證標頭分配給 XMLHTTPREQUEST?
起初,我想使用 XMLHttpRequest 獲取圖像而不使用 Basic Auth:
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Image({
source: new ol.source.ImageWMS({
ratio: 1,
params: { LAYERS: 'ENC', CSBOOL: '2083', CSVALUE: ',,,,,3'},
url: 'https://wms-without-basic-auth.com/?',
imageLoadFunction: function(image, src) {
image.getImage().src = src;
/*
var client = new XMLHttpRequest();
client.open('GET', src, true);
client.setRequestHeader( 'Content-Type', 'image/png' );
client.setRequestHeader( 'Accept', 'image/png' );
client.onload(function() {
image.getImage().src = src;
});
client.send();
*/
},
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([6,54]),
zoom: 6
})
});
imageLoadFunction 僅適用於該行
image.getImage().src = src;
但不是帶有注釋的 XMLHttpRequest。 我認為必須在 client.onload 函數中分配加載的圖像,但我不確定如何執行此操作。 那么我應該如何在 imageLoadFunction 中使用 XMLHttpRequest 呢?
從文檔:
提供自定義 imageLoadFunction 可用於加載帶有 post 請求的圖像,或者 - 通常 - 通過 XHR 請求,其中在加載內容時圖像元素的 src 將設置為數據 URI。
也許嘗試這樣的事情:
imageLoadFunction: function(image, src) {
var client = new XMLHttpRequest();
client.open('GET', src, true);
client.setRequestHeader( 'Content-Type', 'image/png' );
client.setRequestHeader( 'Accept', 'image/png' );
client.responseType = 'blob';
client.onload(function() {
const blob = new Blob(client.response);
const urlData = URL.createObjectURL(blob);
image.getImage().src = urlData;
});
client.send();
},
它能做什么:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.