问题描述:
想用ol5.3实现地图的导出,Openlayers官网有实例,在这里就不写代码了。我自己的代码是加载了geoserver发布的图层,在导出时html页面后台提示错误:
SecurityError: The operation is insecure.
原因是:canvas导出图片时,涉及到跨域的问题,需将图层的crossOrigins设置为“anonymous”
例如:
var wmsSourceLucc = new ol.source.TileWMS({ crossOrigin:'anonymous', //解决错误:SecurityError: The operation is insecure. url: mapWmsURL, params: {'LAYERS': luccLayerParams,tiled: true}, serverType: 'geoserver' });
这样能解决像引入的天地图、谷歌地图、百度地图、OSM地图等的SecurityError: The operation is insecure问题,但是新的问题又来了:自己用geoserver发布的图层又出现了下面的错误
CORS 头缺少 'Access-Control-Allow-Origin'
还是跨域的问题,查了很多技术文档,最终的解决方法是让用于发布geoserver的tomcat支持跨域。具体解决办法:
1、下载jar包
https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/2.6
https://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.9.1
2、将两个jar包拷贝至tomcat的lib文件夹中
3、配置tomcat的web.xml
<filter> <filter-name>CORSfilter-name> <filter-class>com.thetransactioncompany.cors.CORSFilterfilter-class> <init-param> <param-name>cors.allowOriginparam-name> <param-value>*param-value> init-param> <init-param> <param-name>cors.supportedMethodsparam-name> <param-value>GET, POST, HEAD, PUT, DELETEparam-value> init-param> <init-param> <param-name>cors.supportedHeadersparam-name> <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modifiedparam-value> init-param> <init-param> <param-name>cors.exposedHeadersparam-name> <param-value>Set-Cookieparam-value> init-param> <init-param> <param-name>cors.supportsCredentialsparam-name> <param-value>trueparam-value> init-param> filter> <filter-mapping> <filter-name>CORSfilter-name> <url-pattern>/*url-pattern> filter-mapping>
上面的代码放在welcome-file-list之前即可
<welcome-file-list> <welcome-file>index.htmlwelcome-file> <welcome-file>index.htmwelcome-file> <welcome-file>index.jspwelcome-file> welcome-file-list>
4、重启tomcat
问题完美解决!