OpenLayers通过WMS向Geoserver发起GetFeatureInfo请求报错如何解决
问题修复方案
核心错误点
- 生成的GetFeatureInfo请求地址没有编码就直接拼接在代理地址后,URL中包含的
&、=等特殊字符会被代理服务器错误解析,导致请求参数丢失 - 缺少GetFeatureInfo请求必须的
QUERY_LAYERS参数,且现有参数大小写不符合WMS规范、拼写错误 - OpenLayers配置参数拼写错误,导致投影、服务类型配置不生效
- 没有对iframe的加载错误做捕获,无法定位具体返回异常
修正后的完整代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>OpenLayers WMS查询</title> <link rel="stylesheet" href="https://openlayers.org/en/v6.5.0/css/ol.css" type="text/css"> <script src="https://openlayers.org/en/v6.5.0/build/ol.js" type="text/javascript"></script> </head> <body> <div id="map" style="width: 100%; height: 600px;"></div> <div id="info" style="margin-top: 20px;"></div> <!-- 图层切换控件 --> <div> <label><input type="checkbox" value="0" onchange="switchLayer(this)"> Geoserver</label> <label><input type="checkbox" value="1" onchange="switchLayer(this)"> LTU</label> <label><input type="checkbox" value="2" onchange="switchLayer(this)"> GPS</label> </div> <script> var layers = []; layers[0] = new ol.layer.Tile({ source: new ol.source.TileWMS({ url: 'http://localhost:8080/geoserver/AL2/wms?', // 投影配置放在source属性,不属于params参数 projection: 'EPSG:4326', params: { LAYERS: 'AL2:A2', TILED: true, VERSION: '1.1.1' }, // 修正拼写:serverType首字母大写 serverType: 'geoserver' }) }); layers[1] = new ol.layer.Tile({ source: new ol.source.OSM(), visible: false }); layers[2] = new ol.layer.Tile({ source: new ol.source.OSM(), visible: false }); var map = new ol.Map({ target: 'map', layers: layers, view: new ol.View({ center: ol.proj.fromLonLat([13, 56]), zoom: 8, // 修正投影参数名,正确参数为projection projection: 'EPSG:3857' }) }); function switchLayer(evt) { layers[evt.value].setVisible(evt.checked); } map.on('singleclick', function (event) { // 先生成WMS GetFeatureInfo原始地址 const wmsInfoUrl = layers[0].getSource().getFeatureInfoUrl( event.coordinate, map.getView().getResolution(), map.getView().getProjection().getCode(), { INFO_FORMAT: 'text/html', // 补充必填参数QUERY_LAYERS,参数名统一大写 LAYERS: 'AL2:A2', QUERY_LAYERS: 'AL2:A2' } ); if (wmsInfoUrl) { // 对WMS地址做URL编码后再拼接代理地址 const proxyUrl = `../../proxy/proxy.aspx?url=${encodeURIComponent(wmsInfoUrl)}`; document.getElementById('info').innerHTML = `<iframe seamless src="${proxyUrl}" style="width: 100%; border: none;"></iframe>` } }); </script> </body> </html>
排查补充
如果修改后仍有问题,可按以下步骤验证:
- 打开浏览器开发者工具的网络面板,点击地图后复制生成的完整代理请求地址,直接在新标签页打开看返回内容,确认代理是否正确转发请求
- 检查Geoserver对应工作区、图层的权限,是否允许匿名访问GetFeatureInfo接口
- 确认WMS版本和Geoserver支持的版本一致,若使用1.3.0版本需要注意坐标系轴顺序的适配问题
内容的提问来源于stack exchange,提问作者AndHel
相关产品推荐
相关产品推荐

