【问题标题】:How to use XMLHttpRequest with Open Layers如何将 XMLHttpRequest 与开放层一起使用
【发布时间】:2021-01-18 05:35:21
【问题描述】:

我需要使用 Open Layers(和纯 Javascript)从(我公司的)多个 WebMapServers 获取图像。 基本上它有效。问题是某些服务器需要 HTTP 基本身份验证。 OL 文档和相关的 SO 问题说这应该使用 imageLoadFunction 中的 XMLHttpRequest 来完成:

https://openlayers.org/en/latest/apidoc/module-ol_Image.html

How to assign basic authentication header to XMLHTTPREQUEST?

一开始我想获取带有 XMLHttpRequest 而没有基本身份验证的图像:

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 应该如何使用呢?

【问题讨论】:

  • 回复说什么?是有错误,还是根本没有处理?

标签: javascript openlayers wms


【解决方案1】:

来自the docs

提供自定义 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();
},

它的作用:

【讨论】:

  • 谢谢,我需要设置client.responseType = 'blob',现在可以了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 2011-07-24
相关资源
最近更新 更多